24. Swap Nodes in Pairs

LeetCode

Approach 1: Iterative Approach, Time Complexity: O(N), where N is the size of the linked list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy=new ListNode(-1),p=dummy;
dummy.next=head;
while(head!=null && head.next!=null){
p.next=head.next;
head.next=head.next.next;
p.next.next=head;
head=head.next;
p=p.next.next;
}
return dummy.next;
}
}

Approach 2: Recursive Approach, Time Complexity: O(N)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 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;

ListNode firstNode=head;
ListNode secondNode=head.next;

firstNode.next=swapPairs(secondNode.next);
secondNode.next=firstNode;

return secondNode;
}
}

0%