Created
August 13, 2014 05:15
-
-
Save xiren-wang/abf81c547fe0e4f4b1ad to your computer and use it in GitHub Desktop.
Insertion Sort List. Sort a linked list using insertion sort..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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