-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReOrderList.java
More file actions
48 lines (37 loc) · 1.07 KB
/
ReOrderList.java
File metadata and controls
48 lines (37 loc) · 1.07 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
package LinkedLists;
public class ReOrderList {
public static Node findMid(Node head) {
Node slow = head, fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public static Node reverseRecursive(Node head) {
if (head == null || head.next == null) {
return head;
}
Node newHead = reverseRecursive(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
public static void reorderList(Node head) {
Node mid = findMid(head);
Node head2 = mid.next;
mid.next = null;
head2 = reverseRecursive(head2);
Node node = head, temp;
while (node != null || head2 != null) {
if (node == null) return;
temp = node.next;
node.next = head2;
node = node.next;
// Remember this Swap!
head2 = temp;
}
}
public static void main(String[] args) {
}
}