-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedListPartition.java
150 lines (112 loc) · 2.32 KB
/
LinkedListPartition.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
package com.topcoder.easy;
import com.sai.Linkedlist;
public class LinkedListPartition {
ListNode head = null;
ListNode tail = null;
int size = 0;
public void addStart(int data) {
ListNode newNode = new ListNode(data);
if (head == null) {
head = newNode;
tail = newNode;
size++;
} else {
newNode.next = head;
head = newNode;
size++;
}
}
public void addEnd(int data) {
ListNode newNode = new ListNode(data);
if (tail == null) {
head = newNode;
tail = newNode;
size++;
} else {
tail.next = newNode;
tail = newNode;
size++;
}
}
public void display() {
ListNode dummy = head;
while (dummy != null) {
System.out.print(dummy + " -> ");
dummy = dummy.next;
}
}
void ReversePrint(ListNode head) {
if(head!= null)
{
ReversePrint(head.next);
System.out.println(head.data);
}
}
private ListNode partition(ListNode node, int n) {
ListNode beforeStart = null;
ListNode beforeEnd = null;
ListNode afterStart = null;
ListNode afterEnd = null;
while (node != null) {
ListNode next = node.next;
node.next = null;
if (node.data < n) {
if (beforeStart == null) {
beforeStart = node;
beforeEnd = beforeStart;
} else {
beforeEnd.next = node;
beforeEnd = node;
}
} else {
if (afterStart == null) {
afterStart = node;
afterEnd = afterStart;
} else {
afterEnd.next = node;
afterEnd = node;
}
}
node = next;
}
if (beforeStart == null) {
while(beforeStart!=null)
{
System.out.print(afterStart.data+" -> ");
afterStart = afterStart.next;
}
}
beforeEnd.next = afterStart;
while(beforeStart!=null)
{
System.out.print(beforeStart.data);
beforeStart = beforeStart.next;
System.out.print(" -> ");
}
return beforeStart;
}
public static void main(String[] args) {
LinkedListPartition list = new LinkedListPartition();
list.addEnd(5);
list.addEnd(8);
list.addEnd(5);
list.addEnd(10);
list.addEnd(2);
list.addEnd(1);
list.addStart(3);
list.display();
System.out.println();
list.partition(list.head, 5);
list.ReversePrint(list.head);
}
}
class ListNode {
int data;
ListNode next;
ListNode(int data) {
this.data = data;
}
public String toString() {
return data + "";
}
}