abc_begin

导航

219. Insert Node in Sorted Linked List【Naive】

Insert a node in a sorted linked list.

 
Example

Given list = 1->4->6->8 and val = 5.

Return 1->4->5->6->8.

 

解法一:

 1 public class Solution {
 2     public ListNode insertNode(ListNode head, int val) {
 3         
 4         ListNode dummy = new ListNode(0);
 5         dummy.next = head;
 6         ListNode node = new ListNode(val);
 7         
 8         //if val is the smallest in entire list
 9         if (head == null || val < head.val) {
10             dummy.next = node;
11             node.next = head;
12             return dummy.next;
13         }
14         
15         //while val is larger than head.val, loop the linked list and check the range between head & head.next to insert
16         while (head != null && head.next != null) {
17             if (head.val <= val && val <= head.next.val) {
18                 ListNode next = head.next;
19                 head.next = node;
20                 node.next = next;
21                 break;
22             } else if (val > head.next.val) {
23                 head = head.next;
24             }
25         }
26         
27         //if node not inserted in the loop
28         if (head.next == null) {
29             head.next = node;
30         }
31 
32         return dummy.next;
33     }
34 }

方法略显复杂,可以看解法二

参考@linspiration 的代码

 

解法二:

 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 public class Solution {
13     /**
14      * @param head: The head of linked list.
15      * @param val: an integer
16      * @return: The head of new linked list
17      */
18     public ListNode insertNode(ListNode head, int val) { 
19         if (head == null) {
20             return new ListNode(val);
21         }
22         
23         ListNode dummy = new ListNode(0);
24         dummy.next = head;
25         head = dummy;
26         while (head.next != null && head.next.val < val) {
27             head = head.next;
28         }
29         
30         ListNode node = new ListNode(val);
31         node.next = head.next;
32         head.next = node;
33         
34         return dummy.next;
35     }  
36 }

思路
找到相应的位置,并插入这个点。(用dummy node。因为可能插在第一个位置的前面。)
过一遍例子:
0->1->4->6->8->null (当前位置在0,比下一位的值1和插入值5。接着往下走。)
0->1->4->6->8->null(当前位置在1,比下一位的值4和插入值5。接着往下走。)
0->1->4->6->8->null(当前位置在4,比下一位的值6和插入值5。发现6比5大。说明要插在6前面。停止循环。)
我们这时候知道6前面的位置。于是很好办了。插入后链表变成0->1->4->5->6->8->null
最后返回dummy的下一个位置。

参考@ 的代码

https://yeqiuquan.blogspot.com/2016/02/insert-node-in-sorted-linked-list.html

 

 

 

posted on 2017-12-30 18:00  LastBattle  阅读(331)  评论(0编辑  收藏  举报