java - 在已排序的循环链表中插入数据

标签 java linked-list circular-list

我想将给定的数据添加到已经排序的循环链接列表中,以便结果列表也排序。已经提供了 Node 的类,其中包含 public int datapublic Node next 作为类成员。

要实现一个函数addNode(Node head),它将向列表中插入已知数据(9)。 Node head是循环链表的头指针。

我考虑过以下情况

  1. 当列表为空时,创建 Node,将其数据设置为 9 并将其 next 引用到自身。将新创建的节点作为头。

  2. 当列表仅包含一项时。修改第一个节点的 next 指针以指向新节点,并将新节点的 next 指针修改为给定的头节点。让头节点指向值最低的节点。

  3. 当插入的数据是所有数据中最小的,即小于头节点所指向节点的数据时,会插入到头节点之前。

  4. 当要在两个节点之间插入数据时。因此,我使用 while 循环来查找将在其之前插入新数据的节点,并相应地修改该节点的下一个指针。

当我提交代码时,它在某种程度上失败了一个我无法找出的测试用例。有人可以帮我找出我的逻辑中可能忽略的条件吗?

下面是实现的代码:

public static Node addElement(Node input1)
{
    //Write code here
Node result = new Node();
Node current = new Node();
current = input1;

Node value = new Node();
value.data = 10;

if(current == null){
    value.next = value;
    result = value;
}
else if(current.next == current){
    value.next = input1;
    current.next = value;
    result = current.data < value.data ? current : value;
}
else if(value.data < current.data){
    while(current.next != input1)
        current = current.next;     

    current.next = value;
    current.next.next = input1;
    result = current.next;
}   
else{
    while(current.next != input1 && current.next.data <= value.data)
        current = current.next;

    Node currentNext = current.next;
    current.next = value;
    current.next.next = currentNext;
    result = input1;
}

return result;
}

最佳答案

void sortedInsert(struct node** head_ref, struct node* new_node)
{
  struct node* current = *head_ref;

  // Case 1 of the above algo
  if (current == NULL)
  {
     new_node->next = new_node;
     *head_ref = new_node;
  }

  // Case 2 of the above algo
  else if (current->data >= new_node->data)
  {
    /* If value is smaller than head's value then
      we need to change next of last node */
    while(current->next != *head_ref)
        current = current->next;
    current->next = new_node;
    new_node->next = *head_ref;
    *head_ref = new_node;
  }

  // Case 3 of the above algo
  else
  {
    /* Locate the node before the point of insertion */
    while (current->next!= *head_ref && current->next->data < new_node->data)
      current = current->next;

    new_node->next = current->next;
    current->next = new_node;
  }
}

关于java - 在已排序的循环链表中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12490428/

相关文章:

java - Exchange Web 服务 (EWS) Java Api : 401 Unauthorized

java - 为什么当新变量改变时,原来的变量也会改变?

java - 我的循环链表能正常工作吗?

java - RecyclerView 的加载时间问题

c++ - 将节点添加到 LinkedList 不是永久 C++

c++ - 通过指针问题

c# - 链表第一个和最后一个元素不能删除

java - 将两个类(class)合二为一

scala - 迭代循环方式

java - java中的边框布局