您的位置:首页 > 编程语言 > C语言/C++

leetcode之147. Insertion Sort List(C++解法)

2016-09-11 20:14 441 查看
题目:

Sort a linked list using insertion sort.

链表的插入排序

[b]********************************[/b]我是分割线[b]*****************************[/b]

/**

* 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* new_head = new ListNode(0);

ListNode* temp;

ListNode* cur;

new_head->next=head;

temp=new_head;

cur=head;

while(cur)

{

if(cur->next && cur->next->valval)

{

while(temp->next && temp->next->val < cur->next->val)

temp=temp->next;

ListNode* temptemp = temp -> next;

temp->next=cur->next;

cur->next=cur->next->next;

temp->next->next=temptemp;

temp=new_head;

}

else

cur=cur->next;

}

return new_head->next;

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  插入排序 链表