-
Notifications
You must be signed in to change notification settings - Fork 0
/
swappy_nodes.java
69 lines (60 loc) · 1.28 KB
/
swappy_nodes.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
//swapping pairwise nodes
public class Pairnodes
{
Node head;
class Node
{
Node next;
int data;
Node(int d)
{
data=d;
next=null;
}
}
void pairswap()
{
Node temp = head;
while(temp!=null && temp.next!=null)
{
int t = temp.data;
temp.data = temp.next.data;
temp.next.data = t;
temp = temp.next.next;
//here we simply swapped the nodes
}
}
void insert(int element)
{
Node n = new Node(element);
n.next=head;
head = n;
}
void print()
{
Node h=head;
while(h!=null)
{
System.out.print(h.data+" ");
h=h.next;
}
System.out.println();
}
public static void main(String args[])
{
Pairnodes pn = new Pairnodes();
pn.insert(1);
pn.insert(2);
pn.insert(3);
pn.insert(4);
pn.insert(5);
pn.insert(6);
pn.insert(7);
pn.insert(8);
System.out.println("Initial list: ");
pn.print();
pn.pairswap();
System.out.println("Final list ");
pn.print();
}
}