LeetCode: Insertion Sort List 解题报告

Insertion Sort List

Sort a linked list using insertion sort.

SOLUTION:

使用一个dummynode 创建一个新的链,将旧的节点插入到新链中即可,相当简单哦!

 1 /**

 2  * Definition for singly-linked list.

 3  * public class ListNode {

 4  *     int val;

 5  *     ListNode next;

 6  *     ListNode(int x) {

 7  *         val = x;

 8  *         next = null;

 9  *     }

10  * }

11  */

12 public class Solution {

13     public ListNode insertionSortList(ListNode head) {

14         ListNode dummy = new ListNode(0);

15         

16         while (head != null) {

17             ListNode pre = dummy;

18             

19             // 注意,这里要用<= 来保证算法的稳定性

20             // 因为假如有2个数相同,后面的数后找到,也要插入到后面才可以。也就是说当=的时候,是继续往下走

21             while (pre.next != null && pre.next.val <= head.val) {

22                 pre = pre.next;

23             }

24             

25             // unlink the node from the original link. And record the next position.

26             ListNode headNext = head.next;

27             head.next = pre.next;

28             

29             pre.next = head;

30             head = headNext;

31         }

32         

33         return dummy.next;

34     }

35 }
View Code

 

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/list/InsertionSortList.java

你可能感兴趣的:(LeetCode)