LeetCode147. 对链表进行插入排序 c++

取巧(作弊)做法:

/**
 * 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) {
        vector<int> hh;
        ListNode* iter = head;
        while(iter)
        {
            hh.push_back(iter->val);
            iter = iter->next;
        }
        sort(hh.begin(), hh.end());
        iter = head;
        int i = 0;
        while(iter)
        {
            iter->val = hh[i];
            iter = iter->next;
            i++;
        }
        return head;
    }
};

实际应该的做法:

/**
 * 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) {
        ListNode* dummyHead = new ListNode(0);
        ListNode* pre = dummyHead;;  //插入位置的前一个节点
        ListNode* cur = head;
        ListNode* rear; //待排序节点的下一个节点
        while(cur != NULL){
            rear = cur->next;
            while(pre->next != NULL && pre->next->val < cur->val){
                pre = pre->next;
            }
            cur->next = pre->next;
            pre->next = cur;
            cur = rear;
            pre = dummyHead;
        }
        return dummyHead->next;
    }
};
发布了27 篇原创文章 · 获赞 70 · 访问量 9402

猜你喜欢

转载自blog.csdn.net/qq_23905237/article/details/95325667
今日推荐