Sort a linked list using insertion sort.
用插入排序来排序一个list,额, 我写的好麻烦啊, debug了好久,至少提交了5次。。。写吐了快,先贴代码,写的也好乱啊:
1 class Solution { 2 public: 3 ListNode* insertionSortList(ListNode* hed) { 4 if (hed == NULL) return NULL; 5 head = hed; 6 ListNode * insertPosPrev; 7 ListNode * afterP; 8 ListNode * prev = head; 9 ListNode * p = head->next; 10 while (p != NULL) { 11 if (p->val > prev->val){ 12 prev = p; 13 p = p->next; 14 continue; 15 } 16 insertPosPrev = findInsertPos(p); 17 if (insertPosPrev == NULL) {//插入头节点之前 18 afterP = p->next; 19 prev->next = afterP; 20 p->next = head; 21 head = p; 22 p = afterP; 23 continue; 24 } 25 else if (p != insertPosPrev->next) { 26 afterP = p->next; 27 prev->next = afterP; 28 p->next = insertPosPrev->next; 29 insertPosPrev->next = p; 30 p = afterP; 31 continue; 32 } 33 prev = p; 34 p = p->next; 35 } 36 return head; 37 } 38 39 private: 40 ListNode * head; 41 42 ListNode * findInsertPos(ListNode * end) 43 { 44 if (head->val >= end->val) 45 return NULL; //如果插入点在头节点那么返回NULL 46 ListNode * prev = head; 47 ListNode * p = prev->next; 48 while (p != end) { 49 if (prev->val < end->val && p->val >= end->val) 50 return prev; 51 prev = p; 52 p = p->next; 53 } 54 return prev; 55 } 56 };
这里贴一个大神的代码,有时间来看看,暂时还没看懂啊
1 class Solution 2 { 3 public: 4 ListNode *insertionSortList(ListNode *head) 5 { 6 if(head==NULL || head->next==NULL) return head; 7 ListNode *cur=head; 8 ListNode *helper=new ListNode(0); 9 ListNode *pre; 10 while(cur) 11 { 12 ListNode *next=cur->next; 13 pre=helper; 14 while(pre->next!=NULL && pre->next->val<cur->val) 15 { 16 pre=pre->next; 17 } 18 cur->next=pre->next; 19 pre->next=cur; 20 cur=next; 21 } 22 return helper->next; 23 } 24 25 } ;
下面是java写的,第一遍写的基本上可以不看了,写的太麻烦了,下面这个写的稍微简单一点,代码如下:
1 public class Solution { 2 public ListNode insertionSortList(ListNode head) { 3 if(head == null) return null; 4 ListNode helper = new ListNode(Integer.MIN_VALUE);//将第一个节点的值设置成最小的 5 helper.next = head; 6 ListNode p = head.next; 7 ListNode pPre = head; 8 ListNode scan = helper; 9 while(p != null){ 10 if(p.val >= pPre.val){ 11 p= p.next; 12 pPre = pPre.next; 13 }else{ 14 while(p.val > scan.next.val){ 15 scan = scan.next; 16 } 17 if(p.val >= scan.val && p.val <= scan.next.val){ 18 ListNode tmp = scan.next; 19 scan.next = p; 20 pPre.next = p.next; 21 p.next = tmp; 22 p = pPre.next; 23 scan = helper; // 将扫描节点重新放置到链表的前部 24 } 25 } 26 } 27 return helper.next; 28 } 29 }