-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reorder_List.java
56 lines (52 loc) · 1.35 KB
/
Reorder_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
package com.leet_code;
public class Reorder_List {// didn't understand properly
public class ListNode{
int val;
ListNode next;
ListNode(){}
}
public void reorderList(ListNode head) {
if (head == null || head.next == null) {
return;
}
ListNode mid = middleNode(head);
ListNode hs = reverseList(mid);
ListNode hf = head;
while (hf != null && hs != null) {
ListNode temp = hf.next;
hf.next = hs;
hf = temp;
temp = hs.next;
hs.next = hf;
hs = temp;
}
if (hf != null) {
hf.next = null;
}}
public ListNode middleNode(ListNode head) {
ListNode s = head;
ListNode f = head;
while (f != null && f.next != null) {
s = s.next;
f = f.next.next;
}
return s;
}
public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}
ListNode prev = null;
ListNode present = head;
ListNode next = present.next;
while (present != null) {
present.next = prev;
prev = present;
present = next;
if (next != null) {
next = next.next;
}
}
return prev;
}
}