题目描述:
Sort a linked list using insertion sort.
解题思路:
新建一个链表,遍历原链表,将每个节点加入新链表正确的位置
C++实现代码:
/**
* 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)
return NULL;
ListNode *res=new ListNode(0);
ListNode *cur=head;
ListNode *pre=res;
while(cur!=NULL)
{
//保存当前节点下一个节点
ListNode *tmp=cur->next;
pre=res;
//寻找当前节点正确位置的一个节点
while(pre->next!=NULL && pre->next->val < cur->val)
{
pre=pre->next;
}
//将当前节点加入新链表中
cur->next=pre->next;
pre->next=cur;
//处理下一个节点
cur=tmp;
}
return res->next;
}
};