-
Notifications
You must be signed in to change notification settings - Fork 5
/
LinkedListThatIsSortedAlternatingly.java
113 lines (109 loc) · 3.02 KB
/
LinkedListThatIsSortedAlternatingly.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*https://practice.geeksforgeeks.org/problems/linked-list-that-is-sorted-alternatingly/1*/
//without extra space but TLE
class Solution
{
public Node sort(Node head)
{
//your code here, return the head of the sorted list
if (head.next == null) return head;
Node leftList = new Node(-1);
Node rightList = new Node(-1);
Node leftEnd = leftList, rightEnd = rightList, temp = null;
boolean listChoice = true;
while (head != null)
{
if (listChoice)
{
if (leftEnd.data == -1)
{
leftList = leftEnd = head;
}
else
{
leftEnd.next = head;
leftEnd = leftEnd.next;
}
head = head.next;
}
else
{
temp = head.next;
if (rightEnd.data == -1)
{
rightEnd = rightList = head;
rightEnd.next = null;
}
else
{
head.next = rightList;
rightList = head;
}
head = temp;
}
listChoice = !listChoice;
}
if (leftList.data < rightList.data)
{
leftEnd.next = rightList;
rightEnd.next = null;
return leftList;
}
Node newList = new Node(-1), newEnd = newList;
while (leftList != null && rightList != null)
{
if (leftList != null && rightList != null)
{
if (leftList.data < rightList.data)
{
newEnd.next = leftList;
leftList = leftList.next;
}
else
{
newEnd.next = rightList;
rightList = rightList.next;
}
newEnd = newEnd.next;
}
else if (leftList != null)
{
newEnd.next = leftList;
leftList = leftList.next;
newEnd = newEnd.next;
}
else if(rightList != null)
{
newEnd.next = rightList;
rightList = rightList.next;
newEnd = newEnd.next;
}
}
return newList.next;
}
}
class Solution
{
public Node sort(Node head)
{
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder());
while (head != null)
{
pq.add(head.data);
head = head.next;
}
while (!pq.isEmpty())
{
if (head == null)
{
head = new Node(pq.poll());
}
else
{
Node newNode = new Node(pq.poll());
newNode.next = head;
head = newNode;
}
}
return head;
}
}