Insertion Sort List问题及解法

来源:互联网 发布:词典推荐 知乎 魏 编辑:程序博客网 时间:2024/05/24 06:50

问题描述:

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  pre(head->val);pre.next = head;ListNode * ptr = head->next, *tail = head;tail->next = NULL;while (ptr){ListNode * temp = ptr->next;ptr->next = NULL;if (ptr->val >= pre.val){pre.val = ptr->val;tail->next = ptr;                tail = ptr;}else{head = pre.next;ListNode *last = ⪯while (head){if (head->val >= ptr->val){last->next = ptr;ptr->next = head;                        break;}last = head;head = head->next;}}ptr = temp;}return pre.next;    }};


原创粉丝点击