在一有序Linked List中插入一个node,保持有序

例如:给定Linked List 1 --> 3 --> 6 --> 9 --> 13 --> null (要插入int target 0 7 14,分别对应三种情况1.插在最头,2.插在中间,3.插在最后)

ListNode N = new ListNode(target)  // 首先创建一个要插入的node 

case 0 :给定的LinkedList 是null 

 return N;

case 1 : target比first node还要小

 N.next = head;

 return N;

case 2 : target插在中间

                ListNode cur = head; // cur从head开始移动,寻找要插入的位置

要插入的位置:移动cur直到  cur.value < target < cur.next.value

   //找到后插入target

    N.next = cur.next;  // step1  

    cur.next = N;         // step2   

    return head;

stop condition :cur.next.value > target

这里要注意step1和step2的顺序

如果 step1、step2反过来,如下

 cur.next = N;

 N.next = cur.next;// 上一步N已经链接在cur的下一个了,这一步相当于N.next = N;(把N指向自己)

case 3 : target 插在最后一个 (和case 2 同样操作,直到cur.next == null)

        N.next = cur.next;

        cur.next = N

stop condition : cur.next == null

所以case2.case3结合起来stop condition为(cur.next == null || cur.next.value > target)

所以循环条件为stop condition取反(cur.next != null && cur.next.value < target) 

public ListNode insert(ListNode head,int target) {
    // 创建要插入的node
    ListNode N = new ListNode(target);
    // case 0
    if (head == null) {
        return N;
    }
    // case 1
    if (target < head.value) {
        N.next = head;
        return N;
    }
    // case 2 + case 3
    ListNode cur = head; // cur从head开始移动
    while (cur.next != null && cur.next.value < target) {
        cur = cur.next; // 满足循环,移动cur
    }
    
    //把N放到cur和cur.next中间 
    N.next = cur.next;  // 注意这一步和下一步顺序不能反过来
    cur.next = N;
    return head;
}
    
    

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值