File tree 2 files changed +30
-0
lines changed
2 files changed +30
-0
lines changed Original file line number Diff line number Diff line change 31
31
| 20 | [ ValidParentheses] ( https://leetcode.com/problems/valid-parentheses/ ) | [ ![ Java] ( assets/java.png )] ( src/ValidParentheses.java ) [ ![ Python] ( assets/python.png )] ( python/valid_parentheses.py ) | |
32
32
| 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 ) | |
33
33
| 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 ) | |
34
35
| 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 ) | |
35
36
| 27 | [ Remove Element] ( https://leetcode.com/problems/remove-element/ ) | [ ![ Java] ( assets/java.png )] ( src/RemoveElement.java ) [ ![ Python] ( assets/python.png )] ( python/remove_element.py ) | |
36
37
| 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 ) | |
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments