标签:
链表的插入排序
/** * 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 * dummy = new ListNode(-1); dummy->next = head; ListNode * pre = head ; ListNode * cur = head->next ; // 从第二个节点开始 while(cur) { if(pre->val > cur->val) // 这里假设从 头节点到 pre 节点 之间 是排好序的 { ListNode *tmp = dummy; while(tmp->next->val<cur->val) tmp= tmp->next; pre->next = cur->next; // 将pre 与cur 后面的节点连接 cur->next = tmp->next; // cur 插入适当的位置 tmp->next = cur; } else pre = pre->next ; cur = pre->next; } return dummy->next; } };
标签:
原文地址:http://www.cnblogs.com/deanlan/p/4718381.html