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 *sortedHead = new ListNode(-1); while(head != NULL) { //保存head位置 ListNode *temp = head->next; ListNode *cur = sortedHead; while(cur->next != NULL && cur->next->val < head->val) { cur = cur->next; } //插入 head->next = cur->next; cur->next = head; //恢復head head = temp; } return sortedHead->next; } };