Skip to content

Commit f6a449c

Browse files
Create 24 Swap Nodes in Pairs.java
1 parent ed259ed commit f6a449c

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

java/24 Swap Nodes in Pairs.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
//Iterative version
2+
class Solution {
3+
public ListNode swapPairs(ListNode head) {
4+
if (head == null || head.next == null) return head;
5+
ListNode dummy = new ListNode(0);
6+
dummy.next = head;
7+
ListNode temp = dummy;
8+
while (temp.next!=null && temp.next.next!=null) {
9+
ListNode first = temp.next;
10+
ListNode second = temp.next.next;
11+
temp.next = second;
12+
first.next = second.next;
13+
second.next = first;
14+
temp = first;
15+
}
16+
return dummy.next;
17+
18+
}
19+
}
20+
21+
//Recursive version
22+
class Solution {
23+
public ListNode swapPairs(ListNode head) {
24+
if (head == null || head.next == null)
25+
return head;
26+
ListNode p = head.next;
27+
head.next = swapPairs(head.next.next);
28+
p.next = head;
29+
return p;
30+
}
31+
}

0 commit comments

Comments
 (0)