繁体   English   中英

将数据插入已排序的循环链表中

[英]Inserting data in a sorted Circular Linked List

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

将实现一个功能addNode(Node head) ,它将在列表中插入一个已知的data(9)。 Node head是循环链表的头指针。

我考虑了以下情况

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

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

  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;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM