Insert Node in Sorted Linked List

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param head: The head of linked list.
     * @param val: an integer
     * @return: The head of new linked list
     */
    public ListNode insertNode(ListNode head, int val) { 
        // Write your code here
        ListNode dummy = new ListNode(0);
        ListNode node = new ListNode(val);
        dummy.next = head;
         
        ListNode pos = dummy;
        ListNode next = head;
         
        while(pos.next != null && pos.next.val < val){
            pos = pos.next;
            next = next.next;
        }
         
        node.next = next;
        pos.next = node;
         
        return dummy.next;
    }  
}




posted @ 2017-02-14 15:54  copperface  阅读(265)  评论(0编辑  收藏  举报