LeetCode147. 对链表进行插入排序
我的代码:
1 class Solution { 2 public: 3 ListNode* insertionSortList(ListNode* head) { 4 if (!head || !head->next) return head; 5 ListNode *res = head; 6 ListNode *p1 = res; 7 ListNode *pcur = head->next; 8 ListNode *ppre = NULL; //已排序链表的ppre 9 ListNode *pnext = NULL; 10 res->next = NULL;//先将链表断开,分为待插入和已排序两部分 11 while (pcur) { 12 pnext = pcur->next; 13 14 ppre = NULL; 15 p1 = res; 16 while (p1 && p1->val < pcur->val) { 17 ppre = p1; 18 p1 = p1->next; 19 } 20 21 //如果比已排序链表中所有元素都大,则尾插 22 if (p1 == NULL) { 23 ppre->next = pcur; 24 pcur->next = NULL; 25 } 26 //比已排序链表头结点都小,头插 27 else if (ppre == NULL) { 28 pcur->next = res; 29 res = pcur; 30 } 31 //如果在中间某处找到位置,则插入 32 else if (p1->val >= pcur->val) { 33 pcur->next = p1; 34 ppre->next = pcur; 35 } 36 37 pcur = pnext; 38 } 39 return res; 40 } 41 };
LeetCode官方题解代码:
1 class Solution { 2 public: 3 ListNode* insertionSortList(ListNode* head) { 4 if (!head || !head->next) return head; 5 ListNode *dummyHead = new ListNode(0); 6 dummyHead->next = head; 7 ListNode *lastSorted = head, *pcur = head->next; 8 9 while (pcur) { 10 if (lastSorted->val <= pcur->val) { 11 lastSorted = lastSorted->next; 12 } 13 else { 14 ListNode *prev = dummyHead; 15 while (prev->next->val <= pcur->val) { 16 prev = prev->next; 17 } 18 lastSorted->next = pcur->next; 19 //头插 20 pcur->next = prev->next; 21 prev->next = pcur; 22 } 23 pcur = lastSorted->next; 24 } 25 return dummyHead->next; 26 } 27 };
可以看出,我的代码有很多冗余的指针,且判断分支较多,不易读,官方代码就使用了三个指针,非常简洁。