Insertion Sort List

来源:互联网 发布:ubuntu命令行复制文件 编辑:程序博客网 时间:2024/06/01 07:48

Sort a linked list using insertion sort

链表的插入排序

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 *cur = head->next;head->next = NULL;while(cur != NULL){ListNode *next = cur->next;if(cur->val < head->val){cur->next=head;head = cur;}else{ListNode * pre = head, *post = head->next;while(post && cur->val > post->val ){pre = post;post = post->next;}pre->next = cur;cur->next = post;}cur = next;}    return head;}};
刚开始老是报错,结果发现我把判空操作跟val值比较大小的顺序搞颠倒了...不确保非空怎么能比较值了...又脑残了一把

0 0
原创粉丝点击