Skip to content

Commit 4b446eb

Browse files
solves swap nodes in pairs
1 parent 75e6240 commit 4b446eb

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
| 20 | [ValidParentheses](https://leetcode.com/problems/valid-parentheses/) | [![Java](assets/java.png)](src/ValidParentheses.java) [![Python](assets/python.png)](python/valid_parentheses.py) | |
3232
| 21 | [Merge 2 Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | [![Java](assets/java.png)](src/Merge2SortedLists.java) [![Python](assets/python.png)](python/merge_2_sorted_lists.py) | |
3333
| 22 | [Generate Parentheses](https://leetcode.com/problems/generate-parentheses) | [![Java](assets/java.png)](src/GenerateParentheses.java) | |
34+
| 24 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs) | [![Java](assets/java.png)](src/SwapNodesInPairs.java) | |
3435
| 26 | [Remove Duplicates From Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | [![Java](assets/java.png)](src/RemoveDuplicatesFromSortedArray.java) [![Python](assets/python.png)](python/remove_duplicates_from_sorted_array.py) | |
3536
| 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [![Java](assets/java.png)](src/RemoveElement.java) [![Python](assets/python.png)](python/remove_element.py) | |
3637
| 28 | [Needle in Haystack](https://leetcode.com/problems/implement-strstr) | [![Java](assets/java.png)](src/NeedleInHaystack.java) [![Python](assets/python.png)](python/needle_in_haystack.py) | |

src/SwapNodesInPairs.java

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// https://leetcode.com/problems/swap-nodes-in-pairs
2+
// T: O(n)
3+
// S: O(1)
4+
5+
public class SwapNodesInPairs {
6+
private static class ListNode {
7+
int val;
8+
ListNode next;
9+
10+
ListNode(int val, ListNode next) {
11+
this.val = val;
12+
this.next = next;
13+
}
14+
}
15+
16+
public ListNode swapPairs(ListNode head) {
17+
if (head == null || head.next == null) return head;
18+
ListNode newHead = head.next, a = head, b = head.next.next, temp;
19+
head.next.next = head;
20+
while (a != null) {
21+
a.next = (b == null || b.next == null ? b : b.next);
22+
temp = (b == null || b.next == null ? null : b.next.next);
23+
if (b != null && b.next != null) b.next.next = b;
24+
a = b;
25+
b = temp;
26+
}
27+
return newHead;
28+
}
29+
}

0 commit comments

Comments
 (0)