您的位置:首页 > 其它

leedcode——链表插入排序

2017-03-22 16:34 246 查看
题目:Sort a linked list using insertion sort.

思路:定义一个临时链表存放已排序好的链表,将未排序好的节点依次插入。

链表元素:1,3,8,4,6,5,2

(递归到最后一个节点2)

第一轮:temp链表元素为2,head 为5,操作:将5插入到2后面

第二轮:temp链表元素为2,5,head为6,操作:将6插入到5后面

第三轮:temp链表元素为2,5,6,head为4,操作:将4插入到2后面

...

最后一轮:temp链表元素为1,2,3,4,5,6,8

代码:

class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(head == NULL || head->next == NULL) return head;//空链表或只有一个头结点的链表直接返回
ListNode *temp = new ListNode(0);//定义一个临时链表
ListNode *p = temp;
4000

temp->next = insertionSortList(head->next);//递归将已排序好的链表插入临时链表
while(p != NULL && p->next != NULL && head->val > p->next->val){//为head找一个合适的位置
p = p->next;
}
head->next = p->next;//插入head元素
p->next = head;
return temp->next;//返回临时链表
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: