LeetCode解题报告:Insertion Sort List

Insertion Sort List

Sort a linked list using insertion sort.

leetcode subject
思路:
标准的插入排序。考察一下链表的操作。

对链表进行插入排序的正确方法是:新建一个头节点,遍历原来的链表,对原链表的每个节点找到新链表中适合插入位置的前指针,然后执行插入操作。
这种操作链表的题的技巧是:新建一个dummy作为head node,然后把数据插入到dummy的链表中,最后返回dummy.next。

链表的插入排序图示:

注意头结点和头指针的不同,注意用了多少个指针。

1.需要插入排序的链表和带有head node的排好序的链表:寻找到节点插入的位置pre。

2.在pre后面插入节点node(val =4 )

3.开始遍历下一个node(val =2 )。

题解:

 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         // dummy is dummy head node,not head pointer.
15         ListNode dummy = new ListNode(-1);
16         ListNode pre, newNext;
17         ListNode oldNext;
18         while (head != null) {
19             oldNext = head.next;
20             pre = searchInsertPosition(dummy, head.val);
21             newNext = pre.next;
22             pre.next = head;
23             head.next = newNext;
24             head = oldNext;
25         }
26         return dummy.next;
27     }
28 
29     private ListNode searchInsertPosition(ListNode headNode, int val) {
30         ListNode pre = headNode;
31         ListNode nex = pre.next;
32         while ((nex != null) && (nex.val <= val)) {
33             pre = nex;
34             nex = nex.next;
35         }
36         return pre;// inserted position is after pre node.
37     }
38 }
原文地址:https://www.cnblogs.com/byrhuangqiang/p/3784209.html