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) { if(head == NULL || head->next == NULL)return head; ListNode * guide = new ListNode(0); guide->next = head; ListNode * temp = head->next; ListNode * temp_pre = head; while(temp != NULL) { int temp_val = temp->val; ListNode * p = guide->next; ListNode * p_pre = guide; while(temp_val > p->val && p != temp) { p = p->next; p_pre =p_pre->next; } if(p == temp) { temp =temp->next; temp_pre = temp_pre->next; continue; } else { temp_pre ->next =temp->next; p_pre->next =temp; temp->next = p; temp = temp_pre->next; //return guide->next; } } return guide->next; }};