-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwapNode.java
More file actions
65 lines (49 loc) · 1.38 KB
/
SwapNode.java
File metadata and controls
65 lines (49 loc) · 1.38 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
60
61
62
63
64
65
public class SwapNode {
// Function to swap nodes
public static ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
while (prev.next != null && prev.next.next != null) {
ListNode first = prev.next;
ListNode second = prev.next.next;
// Swapping
first.next = second.next;
second.next = first;
prev.next = second;
prev = first;
}
return dummy.next;
}
// Print function
public static void printList(ListNode head) {
ListNode temp = head;
while (temp != null) {
System.out.print(temp.val + " -> ");
temp = temp.next;
}
System.out.println("null");
}
// MAIN METHOD
public static void main(String[] args) {
// Create: 1 -> 2 -> 3 -> 4
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
System.out.print("Before: ");
printList(head);
head = swapPairs(head);
System.out.print("After: ");
printList(head);
}
}
// Separate class
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}