您的位置:首页 > 其它

【Leetcode】Insertion Sort List

2015-11-19 20:29 323 查看
题目链接:https://leetcode.com/problems/insertion-sort-list/

题目:

Sort a linked list using insertion sort.

思路:

头插法。用头结点可以简化插入链表时候的操作,因为要考虑插入链表中间和表头两种情况,插入表头时,head就要更新,还要判断pre指针是否为空

算法:

public ListNode insertSortList(ListNode head, ListNode t) {
ListNode p = head.next, pre = head;// p t pre
while (p != null && p.val < t.val) {
pre = p;
p = p.next;
}
t.next = p;
pre.next = t;
return head;
}

public ListNode insertionSortList(ListNode head) {
ListNode p = head, tmp = p;
ListNode newHead = new ListNode(0); //头结点
while (p != null) {
tmp = p;
p = p.next;
newHead = insertSortList(newHead, tmp);
}
return newHead.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: