-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy path24.Swap_Nodes_in_Pairs.java
57 lines (33 loc) · 1.22 KB
/
24.Swap_Nodes_in_Pairs.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
/**
* If there are more than 1 nodes remaining, we would recursively call the method by passing the
* next.next element.
* This is because we would be swapping the head and the head.next element.
* So, to call the method we would pass the head.next.next element.
* This call will return a head which we would have to attach it to the current head.next element,
AFTER SWAPPING.
*/
ListNode tHead = swapPairs(head.next.next);
/**
* Here, we would write the swapping logic.
* The node which is returned from the above line of code, will be connected with the nodes after
* swapping here.
*/
ListNode temp = head.next;
head.next = tHead;
temp.next = head;
return temp;
}
}