-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwapNodesInPairs.java
More file actions
59 lines (49 loc) · 1.73 KB
/
Copy pathSwapNodesInPairs.java
File metadata and controls
59 lines (49 loc) · 1.73 KB
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
58
59
// Source : https://leetcode.com/problems/swap-nodes-in-pairs/
// Author : cornprincess
// Date : 2020-04-21
/*****************************************************************************************************
*
* Given a linked list, swap every two adjacent nodes and return its head.
*
* You may not modify the values in the list's nodes, only nodes itself may be changed.
*
* Example:
*
* Given 1->2->3->4, you should return the list as 2->1->4->3.
*
******************************************************************************************************/
package SwapNodesInPairs;
public class SwapNodesInPairs {
public ListNode iterative(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prevNode = dummy;
while (head != null && head.next != null) {
// nodes to be swapper
ListNode firstNode = head;
ListNode secondNode = head.next;
// swap nodes
prevNode.next = secondNode;
firstNode.next = secondNode.next;
secondNode.next = firstNode;
// Reinitializing the head and prevNode for next swap
prevNode = firstNode;
head = firstNode.next;
}
return dummy.next;
}
public ListNode recursive(ListNode head) {
// If the list has no node or has only one left.
if (head == null || head.next == null) {
return head;
}
// nodes to be swapped
ListNode firstNode = head;
ListNode secondNode = head.next;
// swap
firstNode.next = recursive(secondNode.next);
secondNode.next = firstNode;
// now the head is second node
return secondNode;
}
}