Description
Sort a linked list using insertion sort.
Example
Given 1->3->2->0->null
, return 0->1->2->3->null
.
解题:用插入法排序链表。很简单的一道题目,但还是出现了很多问题。
总结一下遇到的问题:
(1)没有头结点的情况下,为了方便可以构造一个,返回头结点的next就行了。
(2)没有必要一直在原来的链表上纠结,完全可以申请一个头结点,将原链表结点一个个插进去。
(3)没有必要一上来就考虑怎样写更简单,能做出来才是最重要的,写好了一种方法后可以再优化。
(4)多组测试数据没通过后,要考虑一下算法的可行性,别在一个坑里爬不出来。
代码如下:
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/ public class Solution {
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
public ListNode insertionSortList(ListNode head) {
// write your code here
//新链表的头结点
ListNode dummy = new ListNode(0);
while(head != null){
ListNode node = dummy;
while(node.next != null && node.next.val < head.val){
node = node.next;
}
ListNode temp = head.next;
head.next = node.next;
node.next = head;
head = temp;
}
return dummy.next;
}
}