您的位置:首页 > 其它

LeetCode: Insertion Sort List [147]

2014-07-01 19:30 375 查看

【题目】

Sort a linked list using insertion sort.

【题意】

用插入排序方法排序链表

【思路】

直接搞

【代码】

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* insert(ListNode*head, ListNode*node){
if(head==NULL){
node->next=NULL;
return node;
}

ListNode*prev = NULL;
ListNode*cur = head;
while(cur){
if(cur->val>node->val){
//插入
if(prev==NULL){
//插到链表头
node->next=head;
head = node;
}
else{
//插到链表中
node->next=prev->next;
prev->next=node;
}
return head;
}
else{
prev=cur;
cur=cur->next;
}
}
//插到链表尾
prev->next=node;
node->next=NULL;
return head;
}

ListNode *insertionSortList(ListNode *head) {
if(head==NULL || head->next==NULL)return head;
ListNode*newhead=NULL;
ListNode*cur=head;
ListNode*next=NULL;
while(cur){
next=cur->next;
newhead=insert(newhead, cur);
cur=next;
}
return newhead;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: