We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 8f5380d commit 18fafd6Copy full SHA for 18fafd6
Algorithms Basics/Chapter 2. Linked List/24. Swap Nodes in Pairs.cs
@@ -0,0 +1,23 @@
1
+public class Solution {
2
+ public ListNode SwapPairs(ListNode head) {
3
+ if (head == null || head.next == null) return head;
4
+ ListNode dummy = new ListNode(0);
5
+ dummy.next = head;
6
+ ListNode pre = dummy, temp = null;
7
+ while (head != null && head.next != null) {
8
+ ListNode n1 = head, n2 = head.next;
9
+ // head
10
+ // pre -> n1 -> n2 -> temp...
11
+ // pre -> n2 -> n1 -> temp...
12
+ temp = n2.next;
13
+ pre.next = n2;
14
+ n2.next = n1;
15
+ n1.next = temp;
16
+ // n2 -> pre-> head
17
+ // move to next pair, ...-> n2 -> n1 -> temp ...
18
+ pre = pre.next.next;
19
+ head = temp;
20
+ }
21
+ return dummy.next;
22
23
+}
0 commit comments