Skip to content

Commit 219bc7e

Browse files
authored
Create Reorder List.java
1 parent 08d298b commit 219bc7e

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

LinkedList/Reorder List.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode reverse(ListNode head) {
13+
ListNode pre = null;
14+
ListNode cur = null;
15+
16+
while (head!=null) {
17+
18+
pre = cur;
19+
cur = head;
20+
head = head.next;
21+
cur.next = pre;
22+
}
23+
return cur;
24+
}
25+
public void reorderList(ListNode head) {
26+
//1.find mid
27+
ListNode slow = head;
28+
ListNode fast = head;
29+
30+
while (fast!=null && fast.next!=null) {
31+
slow = slow.next;
32+
fast = fast.next.next;
33+
34+
}
35+
//2. reverse half
36+
ListNode s = reverse(slow.next);
37+
slow.next = null;
38+
39+
while (head!=null && s!=null) {
40+
ListNode nn = head.next;
41+
ListNode rn = s.next;
42+
head.next = s;
43+
head.next.next = nn;
44+
head=nn;
45+
s=rn;
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)