-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion147.java
More file actions
87 lines (73 loc) · 1.7 KB
/
Copy pathQuestion147.java
File metadata and controls
87 lines (73 loc) · 1.7 KB
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
/*
Author: Ananthanarayanan R
Section: Algorithms
Question: 147
*/
import java.util.*;
public class Question147
{
public static ListNode insert(ListNode element, ListNode sortedList)
{
ListNode temp = sortedList;
ListNode prev = null;
ListNode curr = null;
int index =1;
boolean isInserted = false;
//iterate over the sortedList
while(sortedList!=null)
{
if(sortedList.val>element.val)
{
//insert element before sortList
if(index==1) {
element.next = sortedList;
temp = element;
isInserted = true;
break;
}
else
{
prev.next = element;
element.next = sortedList;
isInserted = true;
break;
}
}
index++;
prev = sortedList;
sortedList = sortedList.next;
}
if(!isInserted) // insert in the end
prev.next = element;
return temp;
}
public static ListNode insertionSortList(ListNode head)
{
if(head == null || head.next==null)
return head;
ListNode sortedList = null;
ListNode remainingList = null;
//initial split
remainingList = head;
sortedList = head;
remainingList = head.next;
sortedList.next = null;
//iterateover the remainingList elements
while(remainingList != null)
{
//split the list
ListNode element = remainingList;
remainingList = remainingList.next;
element.next = null;
sortedList = insert(element,sortedList);
}
return sortedList;
}
public static void main(String[] args)
{
ListNode head = LinkedList.create(10,"unsorted");
LinkedList.display(head);
ListNode result = insertionSortList(head);
LinkedList.display(result);
}
}