insertion-sort-list

作者: 美不胜收oo | 来源:发表于2018-12-02 22:59 被阅读0次

    思路

    插入排序,维持两个链表,第一个原始链表,第二个排好序的链表。为了操作方便,第二个链表设置一个哑元dummy。当原始链表为空或者只有一个元素时,直接返回。如果不是,初始化dummy链表。每次从第一个链表中拿出一个元素来排序

    代码

    /**
     * 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(0);
            ListNode* cur = head->next;
            dummy->next = head;
            head->next = NULL;
            
            while(cur != NULL)
            {
                ListNode* next = cur->next;
                ListNode* pos = dummy;
                ListNode* stoppos = dummy->next;
                
                while(stoppos != NULL && cur->val > stoppos->val)
                {
                    pos = stoppos;
                    stoppos = stoppos->next;
                }
                
                pos->next = cur;
                cur->next = stoppos;
                cur = next;
            }
            
            return dummy->next;
            
        }
    };
    

    相关文章

      网友评论

        本文标题:insertion-sort-list

        本文链接:https://www.haomeiwen.com/subject/syzscqtx.html