现在的位置: 首页 > 综合 > 正文

Insertion Sort List –leetcode

2019年04月22日 ⁄ 综合 ⁄ 共 538字 ⁄ 字号 评论关闭

思路:创建一辅助节点,作为生成链表的头结点(不含有效数据)。遍历原链表中每一个节点,并将其插入到新链表的对应位置

/**
 * 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 *dump = new ListNode(0);
        if(head == NULL || head->next == NULL)
            return head;
        ListNode *prev = dump;
        ListNode *cur = head;
        ListNode *tmp;
        while(cur)
        {
            prev = dump;
            while((prev->next != NULL)&&(prev->next->val < cur->val))//找到一点,在该点之后插入
                prev= prev->next;
            tmp = cur->next;
            cur->next = prev->next;
            prev->next = cur;
            cur = tmp;
        }
        return dump->next;
    }
};

抱歉!评论已关闭.