- Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathInsertion-Sort-List.cs
41 lines (38 loc) · 1.2 KB
/
Insertion-Sort-List.cs
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
namespace_147_Insertion_Sort_List
{
publicclassSolution
{
publicListNodeInsertionSortList(ListNodehead)
{
ListNodedummy=newListNode(0);
ListNodeprev=dummy;
while(head!=null)
{
ListNodetemp=head.next;
/* Before insert, the prev is at the last node of the sorted list.
Only the last node's value is larger than the current inserting node
should we move the temp back to the head*/
if(prev.val>=head.val)prev=dummy;
while(prev.next!=null&&prev.next.val<head.val)
{
prev=prev.next;
}
head.next=prev.next;
prev.next=head;
// prev = dummy; // Don't set prev to the head of the list after insert
head=temp;
}
returndummy.next;
}
}
publicclassListNode
{
publicintval;
publicListNodenext;
publicListNode(intval=0,ListNodenext=null)
{
this.val=val;
this.next=next;
}
}
}