我想将给定的数据添加到已经排序的循环链接列表中,以便结果列表也排序。已经提供了 Node
的类,其中包含 public int data
和 public Node next
作为类成员。
要实现一个函数addNode(Node head)
,它将向列表中插入已知数据(9)。 Node head
是循环链表的头指针。
我考虑过以下情况
当列表为空时,创建 Node,将其数据设置为 9 并将其 next 引用到自身。将新创建的节点作为头。
当列表仅包含一项时。修改第一个节点的 next 指针以指向新节点,并将新节点的 next 指针修改为给定的头节点。让头节点指向值最低的节点。
当插入的数据是所有数据中最小的,即小于头节点所指向节点的数据时,会插入到头节点之前。
当要在两个节点之间插入数据时。因此,我使用 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/