[LeedCode OJ]#147 Insertion Sort List

来源:互联网 发布:公众号网页授权域名 编辑:程序博客网 时间:2024/05/10 00:46

【 声明:版权所有,转载请标明出处,请勿用于商业用途。  联系信箱:libin493073668@sina.com】


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


题意:

给定一个链表,要求使用插入排序返回一个排好序的链表


思路:

建立新的链表,按照插入排序的特点,每次循环新链表找到新结点将要插入的位置


/** * 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==nullptr || head->next==nullptr)return head;ListNode *newlist = new ListNode(0);ListNode *cur = head;while(cur){ListNode *ptr = newlist;ListNode *pnext = cur->next;while(ptr && ptr->next && ptr->next->val<cur->val){ptr = ptr->next;}cur->next = ptr->next;ptr->next = cur;cur = pnext;}return newlist->next;}};


0 0
原创粉丝点击