• LF.Insert In Sorted Linked List


     

    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     }

     

  • 相关阅读:
    求第N个素数
    HDU1568
    HDU1003 DP
    POJ 1016 模拟字符串
    POJ 3321 树状数组(+dfs+重新建树)
    UVA12532 线段树(单点更新,区间求乘积的正负)
    POJ2488 dfs
    POJ 1195 二维树状数组
    HDU 4006 优先队列
    优先队列
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8460659.html
Copyright © 2020-2023  润新知