c-了解链表中的节点分配



所以我目前正在学习C中的链表,我对创建链表和插入节点时使用的一些赋值有一些疑问。我希望了解记忆的东西是如何在后台工作的。

struct node {
int data;
struct node *next
}

void createList(int n, struct node *head)
{
struct node *temp, *newnode;

//Assignment 1
temp = head;

//Assignment2
temp->next = newnode
//somethings
}

某些上下文:head不包含任何数据。它只是第一个入口点节点,它指向包含任何数据的第一个节点?temp用于遍历,newnode是新创建的节点,稍后更改为temp

以上两项作业在记忆力方面是如何运作的?在作业1中,我是在复制内容还是两个名称指向同一位置?作业2也有同样的疑问。

更新后,重要代码如下。

int menu()
{
int choice = 0;
printf("nttMENUn1.Create Linked List");
printf("n2.Display Linked List");
printf("nAny other number to exitn");
printf("nEnter Choice : ");
scanf("%d", &choice);
return choice;
}
void createList(int n, struct node *head)
{
int data;
struct node *temp, *newNode;
temp = head; // 'head' node with no data pointing towards 'temp'
for (int i = 1; i <= n; i++)
{
newNode = malloc(sizeof(struct node));
printf("Enter Data %d : ", i);
scanf("%d", &data);
newNode->data = data; // First Node
newNode->next = NULL;
temp->next = newNode;
temp = temp->next;
}
}
void displayList(struct node *head)
{
struct node *temp;
temp = head->next; // Link to First Node
int i = 1;
printf("nStart Displayn");
while (temp != NULL)
{
printf("nData %d : %dn", i, temp->data);
temp = temp->next;
i++;
}
}
void main()
{
int choice, n;
struct node *head;
head = malloc(sizeof(struct node));
head->next = NULL;
label:
choice = menu();
switch (choice)
{
case 1:
printf("Enter Number of Entries : ");
scanf("%d", &n);
createList(n, head);
goto label;
break;
case 2:
displayList(head);
goto label;
break;
default:
printf("Wrong Choice");
exit(0);
break;
}
}

编辑2:另一个疑问:

temp = temp->next

这是用于遍历的,但它是如何工作的next是"structnode"中的子位置,该子位置的地址指向下一个节点,对吗?那么,这个任务在内存位置会发生什么呢?

感谢您的帮助,因为这个话题很难理解。

在这两个赋值中,存储在右侧对象中的值都被赋值给左侧对象。

例如,如果指针头是空指针,则在分配之后

temp = head;

指针temp也将是一个空指针。

如果指针头指向structnode类型的某个对象(节点((存储节点的地址(,则在赋值之后,指针temp也将指向该对象(节点。也就是说,它将存储节点的相同内存地址。

为了使其更加清晰,请考虑以下代码片段。

int x = 10;
int *p = &x;
int *q;
q = p;

赋值后,指针p和q都指向变量x。因此,使用任意一个指针,您都可以访问变量x,例如

printf ( "x = %dn", *q );
*q = 20;
printf ( "x = %dn", *p );

关于功能的附加代码

void createList(int n, struct node *head)
{
int data;
struct node *temp, *newNode;
temp = head; // 'head' node with no data pointing towards 'temp'
for (int i = 1; i <= n; i++)
{
newNode = malloc(sizeof(struct node));
printf("Enter Data %d : ", i);
scanf("%d", &data);
newNode->data = data; // First Node
newNode->next = NULL;
temp->next = newNode;
temp = temp->next;
}
}

然后它有未定义的行为,前提是指针头最初不指向伪节点,并且等于NULL。

最新更新