-
Notifications
You must be signed in to change notification settings - Fork 1
/
InsertionSortForSinglyLinkedList.java
50 lines (37 loc) · 1.09 KB
/
InsertionSortForSinglyLinkedList.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
//User function Template for Java
/*class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
*/
class Solution {
public static Node insertionSort(Node head_ref)
{
if (head_ref == null || head_ref.next == null) {
return head_ref; // Already sorted or empty list
}
Node sortedList = null;
Node current = head_ref;
while (current != null) {
Node next = current.next;
sortedList = sortedInsert(sortedList, current);
current = next;
}
return sortedList;
}
private static Node sortedInsert(Node sortedList, Node newNode) {
if (sortedList == null || sortedList.data >= newNode.data) {
newNode.next = sortedList;
return newNode;
}
Node current = sortedList;
while (current.next != null && current.next.data < newNode.data) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
return sortedList;
}
}