-
Notifications
You must be signed in to change notification settings - Fork 18
/
Fold-a-Linked-List.java
107 lines (88 loc) · 2.13 KB
/
Fold-a-Linked-List.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
107
// Java program to fold a linked list.
// Linked List Class
class LinkedList {
static Node head; // head of the list
/* Node Class */
static class Node {
int data;
Node next;
// Constructor to create a new node
Node(int d)
{
data = d;
next = null;
}
}
void printlist(Node node)
{
if (node == null) {
return;
}
while (node != null) {
System.out.print(node.data + " -> ");
node = node.next;
}
}
Node reverselist(Node node)
{
Node prev = null, curr = node, next;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
node = prev;
return node;
}
void rearrange(Node node)
{
// 1) Find the middle point using tortoise and hare method
Node slow = node, fast = slow.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// 2) Split the linked list in two halves
// node1, head of first half 1 -> 2 -> 3
// node2, head of second half 4 -> 5
Node node1 = node;
Node node2 = slow.next;
slow.next = null;
// 3) Reverse the second half, i.e., 5 -> 4
node2 = reverselist(node2);
// 4) Merge alternate nodes
node = new Node(0); // Assign dummy Node
// curr is the pointer to this dummy Node, which will be used to form the new list
Node curr = node;
while (node1 != null || node2 != null) {
// First add the element from first list
if (node1 != null) {
curr.next = node1;
curr = curr.next;
node1 = node1.next;
}
// Then add the element from second list
if (node2 != null) {
curr.next = node2;
curr = curr.next;
node2 = node2.next;
}
}
// Assign the head of the new list to head pointer
node = node.next;
}
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
list.printlist(head); // print original list
list.rearrange(head); // rearrange list as per ques
System.out.println("");
list.printlist(head); // print modified list
}
}