我是一个新学习者,正在尝试建立链表。我可以这样做,但我试图保留根节点或第一个节点的指针,因此在构建链表后,我可以读取列表或执行模式匹配,但我无法成功。你能在这里帮忙吗?
#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
int main(){
int d;
struct node *linked;
struct node *head;
linked = malloc (sizeof(struct node));
head = linked; <<<< As this is pointer, in while loop whenever malloc executes it changes the value of head as well.
printf ("Location of head %p \n", head->next);
d = 1;
while (d>0){
printf ("Enter the value of X: ");
scanf ("%d", &linked->x);
linked->next = malloc (sizeof(struct node));
printf ("Location of linked %p \n", linked->next);
printf ("Location of head %p \n", head->next);
printf ("To enter further value enter non zero: ");
scanf ("%d", &d);
if (d==0)
linked->next = NULL;
}
//linked->next = NULL;
printf("Value of Next is %p\n", linked->next);
printf ("Location of head %p \n", head->next);
}
输出:
MacBook-Air:cprog jimdev$ ./a.out
头部位置 0x7fff90ab952c <<<< 这个值不应该改变,但在随后的输出中它是。
输入 X 的值:0
链接 0x7ff0624039c0 的位置
头部位置 0x7ff0624039c0 <<<< 与前一个不同的值
要输入更多值,请输入非零:3
输入 X 的值:3
链接 0x7ff0624039d0 的位置
头部位置 0x7ff0624039d0 <<<< 与前一个不同的值
要输入更多值,请输入非零:0
Next 的值为 0x0
头 0x0 的位置
我刚刚尝试了这个新的,它也执行链表元素的 printf,如果你们想到任何改进,请告诉我。我知道递归是实现它的快速而简洁的方法,但我想用 while 循环尝试一些东西。
包括
包括
结构节点{
int x;
struct node *next;
};
诠释主要(){
int d, hold, i;
struct node *list;
struct node *head;
struct node *current;
list = (node *)malloc(sizeof(struct node));
head = list;
printf ("Location of list is %p \n", head);
d = 1;
而(d>0){
printf ("Enter the value of X: ");
scanf ("%d", &list->x);
printf ("Location of list is %p\n", list);
current = (node *)malloc (sizeof (struct node));
list->next = current;
list = current;
printf ("Location of head is %p\n", head);
printf ("Enter zero to terminate the loop: ");
scanf ("%d", &d);
}
list->next = NULL;
printf ("Value of last next is %d\n", list->next);
current = head;
i = 1;
while (current->next != 0){
printf ("Location of list is %p \n", current);
printf ("Value of linked list %d elements %d \n", i, current->x);
current = current->next;
i++;
}
scanf ("%d", &hold);
}