zoukankan      html  css  js  c++  java
  • 循环有序链表的插入

    给定循环升序列表中的一个点,写一个函数向这个列表中插入一个新元素,使这个列表仍然是循环升序的。给定的可以是这个列表中任意一个顶点的指针,并不一定是这个列表中最小元素的指针。

    如果有多个满足条件的插入位置,你可以选择任意一个位置插入新的值,插入后整个列表仍然保持有序。

    如果列表为空(给定的节点是 null),你需要创建一个循环有序列表并返回这个点。否则。请返回原先给定的节点。

    下面的例子可以帮你更好的理解这个问题:

     

    在上图中,有一个包含三个元素的循环有序列表,你获得值为 3 的节点的指针,我们需要向表中插入元素 2。


     

    新插入的节点应该在 1 和 3 之间,插入之后,整个列表如上图所示,最后返回节点 3。

    解答1:

    public static Node insert(Node head, int insertVal) {
        /*新节点*/
        Node ins = new Node(insertVal);
        /*头节点是空,构造单节点循环链表返回*/
        if (null == head) {
          ins.next = ins;
          return ins;
        }
        /*记录最大值节点*/
        Node max = head;
        Node temp = head;
        while (temp.next != head) {
          Node next = temp.next;
          /*寻找符合升序条件的节点*/
          if (temp.val <= insertVal && insertVal <= next.val) {
            temp.next = ins;
            ins.next = next;
            return head;
          }
          temp = next;
          if (temp.val >= max.val) {
            max = temp;
          }
        }
        if (temp.val <= insertVal && insertVal <= temp.next.val) {
          Node next = temp.next;
          temp.next = ins;
          ins.next = next;
          return head;
        }
        /*没有满足升序的节点,将insertVal插入到最大值节点后面*/
        Node next = max.next;
        max.next = ins;
        ins.next = next;
        return head;
      }
    View Code

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/insert-into-a-cyclic-sorted-list

  • 相关阅读:
    leetcode_138复制带随机指针的链表
    minSTL
    LLVM
    STL基础_迭代器
    mysql数据库表清空后id如何从1开始自增
    explain用法和结果分析
    MySQL多表查询与子查询
    数据结构与算法笔记
    MySQL数据库的SQL语言与视图
    mysql忘记密码解决方案
  • 原文地址:https://www.cnblogs.com/wuyouwei/p/11834224.html
Copyright © 2011-2022 走看看