Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Created August 13, 2014 05:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/abf81c547fe0e4f4b1ad to your computer and use it in GitHub Desktop.
Save xiren-wang/abf81c547fe0e4f4b1ad to your computer and use it in GitHub Desktop.
Insertion Sort List. Sort a linked list using insertion sort..
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
ListNode * newHead = NULL;
while(head) {
ListNode *next = head->next;
head->next = NULL; //cut off
if (!newHead) {
newHead = head;
}
else {
ListNode * prev = NULL;
ListNode * scan = newHead;
while(scan && scan->val <= head->val) {
prev = scan;
scan = scan->next;
}
//scan->val > head->val
// newHead -> ... -> head -> scan
if (prev) {
prev->next = head;
head->next = scan;
}
else { //prev=NULL, head -> scan
head->next = newHead;
newHead = head;
}
}
head = next;
}
return newHead;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment