该程序基于链表。它每次都会在列表的开头添加元素 Insert(x)
被称为 main()
。代码中的大箭头指向我不确定是否正确的部分。我的问题列举如下:
问题 1。该代码创建 global structure pointer head
Node 类型和指向结构 Node
的本地指针在 Insert()
功能。第一个箭头指向执行 temp->next = head
的代码。这是否意味着我们传入 temp->next 是 head 的地址或 head 内部的值?我猜这个值——请确认。
假设我有案例:
int a= 2;
int *p;
然后p= &a;
意味着 p
地址为a
但这里的代码看起来像 p=a
即指针temp->next = head
这里是next pointer= head
意味着我们正在头节点内部传递值。如果它是地址,我们应该使用 &head
?
问题 2。在下一个箭头 head = temp
。我清楚地看到我们正在将 temp 的地址传递给 head?这是对的吗?或者是说 temp 的地址到 temp 的地址?
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
};
struct Node* head;
void Insert(int x)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data=x;
temp->next = head; <------------------------------- (1)
head= temp; <------------------------------- (2)
}
void Print()
{
struct Node * temp= head;
printf("List is: ");
while(temp != NULL)
{
printf("%d ", temp->data);
temp= temp->next;
}
printf("\n");
}
int main()
{
head =NULL;
int n, i, x;
printf("How many Numbers?: \n");
scanf("%d", &n);
for(i= 0; i<n; i++)
{
printf("Enter the number: ");
scanf("%d",&x);
Insert(x);
Print();
}
return 0;
}
最佳答案
您的第一个问题:
您声明一个名为 head 的指针:
struct Node* head;
指针是指向内存中值的地址。 当你这样做时:
temp->next = head;
然后将指针head分配给temp->next。所以并不是head的值,而是指向该值的地址。
你的第二个问题:
首先声明一个指针 temp 并为其分配一些内存:
struct Node* temp = malloc(sizeof(struct Node));
然后将其分配给 head(头指针现在指向临时分配的内存):
head= temp;
两者都是指针,因此将temp指针保存在head指针中。而已。例如: 假设您的 head 指针指向地址 0001。而您的 temp 指针指向地址 0002。如果您执行 head = temp,则 >head将指向地址0002。
示例:
struct Node node1;
node1 不是指针,因此它具有值。如果你想从值中创建一个指针,那么你需要获取node1的地址:
struct Node *node1Pointer = &node1;
&node1表示node1的地址。
如果现在您想要 node1 的值并从 node1Pointer 获取它,那么您必须取消引用它:
struct Node node2 = *node1Pointer;
*nodePointer 的意思是,给我这个指针指向的值。
现在假设您有一个节点1,它有一个地址为0001的指针node1Pointer。并且您还有另一个节点node2,它有一个node2Pointer指向地址0002。
考虑以下因素:
struct Node *tempNodePointer = node2Pointer;
tempNodePointer指向地址0002
node2Pointer = node1Pointer;
node2Pointer现在指向地址0001
node1Pointer = 0;
node1Pointer 现在指向任何内容,空指针
struct Node nodeValue = *node2Pointer;
nodeValue 现在具有存储在地址 0001 处的值
node1Pointer = &nodeValue;
node1Pointer现在指向地址0001
这可能会更好一些。
希望对你有帮助。
关于c - 在链表开头插入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25161849/