173. Insertion Sort List【LintCode by java】

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)多组测试数据没通过后,要考虑一下算法的可行性,别在一个坑里爬不出来。

代码如下:

 1 /**
 2  * Definition for ListNode
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 
13 public class Solution {
14     /**
15      * @param head: The first node of linked list.
16      * @return: The head of linked list.
17      */
18     public ListNode insertionSortList(ListNode head) {
19         // write your code here
20         //新链表的头结点
21         ListNode dummy = new ListNode(0);
22         while(head != null){
23             ListNode node = dummy;
24             while(node.next != null && node.next.val < head.val){
25                 node = node.next;
26             }
27             ListNode temp = head.next;
28             head.next = node.next;
29             node.next = head;
30             head = temp;
31         }
32         return dummy.next;
33     }
34 }

 

转载于:https://www.cnblogs.com/phdeblog/p/9190194.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值