-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPairSwapLL[LL].java
106 lines (91 loc) · 2.49 KB
/
PairSwapLL[LL].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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// { Driver Code Starts
import java.util.*;
import java.lang.*;
class Node {
int data;
Node next;
Node(int key) {
data = key;
next = null;
}
}
class Swap {
static Node head;
static Node last;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t > 0) {
int n = sc.nextInt();
int a1 = sc.nextInt();
Node head = new Node(a1);
addToTheLast(head);
for (int i = 1; i < n; i++) {
int a = sc.nextInt();
addToTheLast(new Node(a));
}
GfG gfg = new GfG();
head = gfg.pairwiseSwap(head);
printList(head);
System.out.println();
t--;
}
}
public static void addToTheLast(Node node) {
if (head == null) {
head = node;
last=head;
} else {
// Node temp = head;
// while (temp.next != null) temp = temp.next;
last.next = node;
last=last.next;
}
}
public static void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
}// } Driver Code Ends
/*node class of the linked list
class Node
{
int data;
Node next;
Node(int key)
{
data = key;
next = null;
}
}*/
// complete the below function
class GfG {
public static Node pairwiseSwap(Node node) {
Node head = node;
if(head==null || head.next==null)
return head;
//before swapping,store the head as 2nd node in LL
head = head.next;
Node prevPair = null;
Node nextPair = null;
Node temp = node;//start the swapping process from 1st node
do {//swap the pairs while tracking prev pairs and next pairs
if(temp.next != null){
nextPair = temp.next.next;
} else {//LL size is odd, just exit the loop
break;
}
nextPair = temp.next.next;
temp.next.next = temp;//pair swap
if(prevPair != null)
prevPair.next = temp.next;//prevpair should hold swapped 2nd node
temp.next = nextPair;//pair swap
prevPair = temp;
temp = nextPair;
}while(nextPair != null);
//end of do while loop
return head;
}
}