forked from Shreyasheeetal20/HACKTOBERFEST22
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreorderList.java
43 lines (33 loc) · 966 Bytes
/
reorderList.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
// Reorder list problem of leetcode
class Solution {
public void reorderList(ListNode head) {
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
ListNode first = head;
ListNode second = reverse(slow.next);
slow.next = null;
while(second != null){
ListNode temp1 = first.next;
ListNode temp2 = second.next;
first.next = second;
second.next = temp1;
first = temp1;
second = temp2;
}
}
public static ListNode reverse(ListNode head){
ListNode cur = head;
ListNode prev = null;
while(cur!=null){
ListNode temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
}
}