标签:链表
题目
Sort a linked list using insertion sort.
解答
链表无法像数组那样从后往前依次比较插入,只能从前往后;在链表首部添加一个哨兵可以稍微简化下代码,代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode ret = new ListNode(-1);
ListNode cur = head;
ListNode pre = ret;
while(cur!=null){
ListNode tmp = cur;
cur=cur.next;
if(pre.next==null){
pre.next=tmp;
tmp.next=null;
pre=ret;
}else {
while(pre.next!=null&&pre.next.val<tmp.val){
pre=pre.next;
}
tmp.next=pre.next;
pre.next=tmp;
pre=ret;
}
}
return ret.next;
}
}
---EOF---
【LeetCode】Insertion Sort List,布布扣,bubuko.com
标签:链表
原文地址:http://blog.csdn.net/navyifanr/article/details/37598011