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     }

 

 

 

转载于:https://www.cnblogs.com/davidnyc/p/8460659.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值