Skip to content

Commit 7e68ede

Browse files
author
Li Li
committed
add recursion to 24
1 parent ca04bda commit 7e68ede

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

Algorithms Basics/Chapter 2. Linked List/24. Swap Nodes in Pairs.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// iteration
12
public class Solution {
23
public ListNode SwapPairs(ListNode head) {
34
if (head == null || head.next == null) return head;
@@ -20,4 +21,15 @@ public ListNode SwapPairs(ListNode head) {
2021
}
2122
return dummy.next;
2223
}
24+
}
25+
26+
// recursion
27+
public class Solution2 {
28+
public ListNode SwapPairs(ListNode head) {
29+
if (head == null || head.next == null) return head;
30+
ListNode n = head.next;
31+
head.next = SwapPairs(n.next);
32+
n.next = head;
33+
return n;
34+
}
2335
}

0 commit comments

Comments
 (0)