[leetcode] 147. Insertion Sort List 解题报告

题目链接:https://leetcode.com/problems/insertion-sort-list/

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 || !head->next) return head;
        ListNode* pHead = new ListNode(0);//创建虚拟头节点
        pHead->next = head;
        ListNode *p = head->next;
        head->next = NULL;
        while(p)
        {
            ListNode *q = p->next, *k = pHead;
            while(k->next && k->next->val < p->val)//查找要插入的位置
                k = k->next;
            p->next = k->next;
            k->next = p;
            p = q;
        }
        head = pHead->next;
        delete pHead;
        return head;
    }
};


你可能感兴趣的:(LeetCode,链表)