-
Notifications
You must be signed in to change notification settings - Fork 820
/
SwapNodesInPairs.java
58 lines (53 loc) · 1.54 KB
/
SwapNodesInPairs.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
58
/* (C) 2024 YourCompanyName */
package linked_list;
/**
* Created by gouthamvidyapradhan on 13/08/2017. Given a linked list, swap every two adjacent nodes
* and return its head.
*
* <p>For example, Given 1->2->3->4, you should return the list as 2->1->4->3.
*
* <p>Your algorithm should use only constant space. You may not modify the values in the list, only
* nodes itself can be changed.
*/
public class SwapNodesInPairs {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static void main(String[] args) throws Exception {
ListNode node = new ListNode(1);
node.next = new ListNode(2);
node.next.next = new ListNode(3);
node.next.next.next = new ListNode(4);
node.next.next.next.next = new ListNode(5);
node.next.next.next.next.next = new ListNode(6);
ListNode head = new SwapNodesInPairs().swapPairs(node);
while (head != null) {
System.out.println(head.val);
head = head.next;
}
}
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = head.next;
ListNode curr = head.next;
ListNode prev = head;
ListNode prevPrev = new ListNode(-1); // dummy node
while (curr != null) {
prev.next = curr.next;
curr.next = prev;
prevPrev.next = curr;
if (prev.next != null) {
curr = prev.next.next;
prev = prev.next;
prevPrev = prevPrev.next.next;
} else {
curr = null;
}
}
return newHead;
}
}