-
Notifications
You must be signed in to change notification settings - Fork 0
/
Test5-Sort Linked List
61 lines (54 loc) · 1.83 KB
/
Test5-Sort Linked List
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
Given a Linked List, which has nodes in alternating ascending and descending orders. Sort the list efficiently and space complexity should be O(1).
You just need to return the head of sorted linked list, don't print the elements.
Input format :
Line 1 : Linked list elements of length L (separated by space and terminated by -1)
Line 2 : Integer n
Output format :
Updated list elements (separated by space)
Sample Input 1 :
10 40 53 30 67 12 89 -1
Sample Output 1 :
10 12 30 40 53 67 89
****************************************Solution***********************************
public class Solution {
public static LinkedListNode<Integer> sort(LinkedListNode<Integer> head) {
if(head==null || head.next==null)
return head;
for(int i=0;i<lengthLL(head)-1;i++)
{
LinkedListNode<Integer> prev = null;
LinkedListNode<Integer> curr = head;
LinkedListNode<Integer> next = curr.next;
while(curr.next != null)
{
if(curr.data > curr.next.data)
{
if(prev == null){
curr.next = next.next;
next.next = curr;
prev = next;
head = prev;
}else{
next = curr.next;
curr.next = next.next;
prev.next = next;
next.next = curr;
prev = next;
}
}else{
prev = curr;
curr = curr.next;
}
}
}
return head;
}
private static int lengthLL(LinkedListNode<Integer> head){
int count = 1;
while(head.next != null){
head = head.next;
count++;
}
return count;
}
}