C 在循环链表的开头插入
我最近一直在研究循环链表,大多数人编写代码的方式如下所示:C 在循环链表的开头插入,c,pointers,linked-list,C,Pointers,Linked List,我最近一直在研究循环链表,大多数人编写代码的方式如下所示: #include<stdio.h> #include<stdlib.h> /* structure for a node */ struct Node { int data; struct Node *next; }; /* Function to insert a node at the begining of a Circular linked list */ void push(s
#include<stdio.h>
#include<stdlib.h>
/* structure for a node */
struct Node
{
int data;
struct Node *next;
};
/* Function to insert a node at the begining of a Circular
linked list */
void push(struct Node **head_ref, int data)
{
struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp = *head_ref;
ptr1->data = data;
ptr1->next = *head_ref;
/* If linked list is not NULL then set the next of last node */
if (*head_ref != NULL)
{
while (temp->next != *head_ref)
temp = temp->next;
temp->next = ptr1;
}
else
ptr1->next = ptr1; /*For the first node */
*head_ref = ptr1;
}
/* Function to print nodes in a given Circular linked list */
void printList(struct Node *head)
{
struct Node *temp = head;
if (head != NULL)
{
do
{
printf("%d ", temp->data);
temp = temp->next;
}
while (temp != head);
}
}
/* Driver program to test above functions */
int main()
{
/* Initialize lists as empty */
struct Node *head = NULL;
/* Created linked list will be 11->2->56->12 */
push(&head, 12);
push(&head, 56);
push(&head, 2);
push(&head, 11);
printf("Contents of Circular Linked List\n ");
printList(head);
return 0;
}
但是,有一件事是在循环链表的开头插入时永远无法理解的。如果我们的最后一个节点总是指向第一个节点,也就是说最后一个节点*下一个指针的地址与*第一个指针的地址相同,那么为什么要在第一个节点之后插入项目,我们必须遍历整个列表并更新最后一个节点的*下一个指针,以将新添加的节点指向开头。而不是while循环为什么我们不能这样做:
节点*新增
新增->下一步=第一步->下一步
第一个=新添加的
因为*第一个指针有第一个节点的地址,所以如果我们更新*第一个指针,那么已经指向第一个指针的最后一个指针也应该更新自身。
为什么要旅行整个名单 因为列表是循环的,所以列表的最后一个元素需要指向列表的第一个元素。将新元素插入列表开头时,列表的第一个元素已更改为其他元素。要保持循环,必须找到最后一个元素并使其指向新的第一个元素 提高操作效率的一种方法是维护循环链表的尾部,而不是头部。然后插入到尾部和头部都可以在固定的时间内完成
这是真正的C,而不是C++。在单链表中,只有一个方向可以移动。头部不知道尾部在哪里,它只知道下一个节点在哪里,与列表中的其他节点相同。现在,如果你实现了一个双链表,那么头部确实知道尾部在哪里,因为它知道下一个和上一个节点在哪里。谢谢你的回答。但是,假设我在开头有一个元素,它看起来像:temp->next=first->next first=temp,现在我的问题是:如果我们更新了第一个节点,那么最后一个节点不应该更新自己,因为它总是指向*第一个指针最后一个元素的下一个指针没有改变它的值,所以它必须更新。例如int x,y;y=1;x=y;y=2;。在那个序列之后,x仍然是1。同样,最后一个元素上的下一个指针仍然指向旧的第一个元素,而不是新的。谢谢您的帮助。还有一个问题。如果x和y是指针,我说x=y。它是指x指向y指向的地址,还是说x是指向y的指针?对于x=y,这意味着x和y指向同一个对象。对于x=&y,这意味着x指向y。