Description
Insert a value in a sorted linked list.
Examples
- L = null, insert 1, return 1 -> null
- L = 1 -> 3 -> 5 -> null, insert 2, return 1 -> 2 -> 3 -> 5 -> null
- L = 1 -> 3 -> 5 -> null, insert 3, return 1 -> 3 -> 3 -> 5 -> null
- L = 2 -> 3 -> null, insert 1, return 1 -> 2 -> 3 -> null
1 public ListNode insert(ListNode head, int value) {
2 // Write your solution here
3 ListNode target = new ListNode(value);
4 if (head == null || head.value >= target.value){
5 target.next = head ;
6 return target ;
7 }
8 ListNode curr = head ;
9 ListNode pre = null ;
10 while (curr != null){
11 if (curr.value < target.value){
12 pre = curr;
13 curr = curr.next ;
14 }
15 /* 1-> 2-> 5->6 target 4
16 p c
17 这个和下面的CORNER CASE 是一个处理方法
18 * */
19 else{
20 break;
21 }
22 }
23 //corner case: [1 2 3] target: 5
24 pre.next = target ;
25 target.next = curr ;
26 return head ;
27 }
这是重要的方法, 远远比上面的版本好: dummy head 避免了 头部不确定,头部为空的各种情况
1 public ListNode insert(ListNode head, int value) { 2 // Write your solution here 3 ListNode dummy = new ListNode(0); 4 dummy.next = head ; 5 ListNode pre = dummy ; 6 ListNode curr = head ; 7 while (curr != null && curr.val<=value){ 8 pre = curr ; 9 curr = curr.next ; 10 } 11 ListNode target = new ListNode(value) ; 12 pre.next = target ; 13 target.next = curr ; 14 //work for both cases: before head or in the middle 15 return dummy.next ; 16 }