-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path143. Reorder List.java
76 lines (62 loc) · 1.69 KB
/
143. 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
// Your code here
if(head == null || head.next == null)
return;
ListNode mid = midElement(head);
ListNode nhead = mid.next;
mid.next = null;
nhead = reverse(nhead);
ListNode c1 = head;
ListNode c2 = nhead;
ListNode f1 = null;
ListNode f2 = null;
while(c1 != null && c2 != null)
{
f1 = c1.next;
f2 = c2.next;
c1.next = c2;
c2.next = f1;
c1 = f1;
c2 = f2;
}
}
ListNode midElement(ListNode head)
{
if(head == null || head.next == null)
return head;
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null)
{
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
ListNode reverse(ListNode head)
{
if(head == null || head.next == null)
return head;
ListNode curr = head;
ListNode prev = null;
while(curr != null)
{
ListNode forw = curr.next;
curr.next = prev;
prev = curr;
curr = forw;
}
return prev;
}
}