-
Notifications
You must be signed in to change notification settings - Fork 5
/
ReorderList.java
89 lines (81 loc) · 2.7 KB
/
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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
/*https://leetcode.com/problems/reorder-list/*/
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null) return;
ListNode tortoise = head, hare = head, prev = tortoise;
while (hare != null && hare.next != null)
{
prev = tortoise;
tortoise = tortoise.next;
hare = hare.next.next;
}
if (hare != null) tortoise = prev;
ListNode secondList = tortoise.next;
tortoise.next = null;
//reversing the second list
secondList = reverse(secondList);
ListNode newList = new ListNode(-1), tempPoint = newList;
boolean turn = true;
while (head != null && secondList != null)
{
if (turn)
{
tempPoint.next = head;
head = head.next;
}
else
{
tempPoint.next = secondList;
secondList = secondList.next;
}
tempPoint = tempPoint.next;
turn = !turn;
}
if (head != null) tempPoint.next = head;
else if (secondList != null) tempPoint.next = secondList;
head = newList.next;
}
private ListNode reverse(ListNode head)
{
if (head.next == null) return head;
ListNode reversedList = reverse(head.next);
head.next.next = head;
head.next = null;
return reversedList;
}
}
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null) return;
ListNode tortoise = head, hare = head, prev = tortoise;
while (hare != null && hare.next != null)
{
prev = tortoise;
tortoise = tortoise.next;
hare = hare.next.next;
}
if (hare != null) tortoise = prev;
ListNode secondList = tortoise.next;
tortoise.next = null;
//reversing the second list
secondList = reverse(secondList);
head = getInterleavedList(head,secondList);
}
private ListNode getInterleavedList(ListNode head1, ListNode head2)
{
if (head1 == null) return head2;
if (head2 == null) return head1;
ListNode interleavedList = getInterleavedList(head1.next,head2.next);
head1.next = head2;
head2.next = interleavedList;
return head1;
}
private ListNode reverse(ListNode head)
{
if (head.next == null) return head;
ListNode reversedList = reverse(head.next);
head.next.next = head;
head.next = null;
return reversedList;
}
}