LeetCode—Insertion Sort List

对链表进行插入排序。


插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。

插入排序算法:

  1. 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
  2. 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
  3. 重复直到所有输入数据插入完为止。

 //* 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 *cur = head;
        ListNode *helper = new ListNode(-1);
        ListNode *pre = helper;
        ListNode *next = cur->next;
        
        while(cur){
            next = cur->next;//保存cur的值
            pre = helper;
            while(pre->next != NULL && cur->val > pre->next->val)
                pre = pre->next;
            cur->next = pre->next;
            pre->next = cur;
            cur =next;                       
        }
        return helper->next;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_37992828/article/details/81161008