leetcode 147 Insertion Sort List

思路 :首先要知道插入排序的思想  就是从前往后遍历 当遇到一个数比前面的数小的时候 就把这个数 拿出来  把它插入它应该在的位置;

所以 就要 当前结点的前一个结点的下一个结点 指向这个结点的下一个结点也就是

pre-->cur--->pNext;

pre->next=pNext;

把cur这个结点拿出来 将它插入它应该在的位置;

  需要从前遍历 如果结点比这个结点的值小 那么 直接往后遍历 知道遇到比它大的值;

代码就简单了 如下:

/**
 * 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 *dummy=new ListNode(0);
        dummy->next=head;
        ListNode *cur=head;
        while(cur&&cur->next)
        {
            if(cur->val>cur->next->val)
            {
                ListNode *temp=cur->next;//将这个节点取出来;
                cur->next=temp->next;//它的前一个结点的下一个结点指向它的下一个结点 也就是将它取出来;
                ListNode *pre=dummy;
                while(pre->next&&pre->next->val<temp->val)//从前往后遍历找到它应该在的位置;
                    pre=pre->next;
                temp->next=pre->next;
                pre->next=temp;
            }
            else 
                cur=cur->next;
        }
            return dummy->next;
    }
};

猜你喜欢

转载自blog.csdn.net/langxue4516/article/details/81463312