在C中添加到列表和显示列表功能
我有我创建的链接列表。我制作了AddTostart函数,该函数具有HAS2参数,第一个参数是列表的负责人,第二个参数是要插入节点中的数据。我还有DisplayList,该列表仅显示列表中的内容。
代码:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node* addToStart(struct node* head, int d){
struct node *new = malloc(sizeof(struct node));
if(new == NULL){
printf("out of memory");
}
else{
new->data = d;
new->next = NULL;
new->next = head;
head = new;
return head;
}
return 0;
}
void displayList(struct node* head){
struct node *ptr = head;
while(ptr != NULL){
printf("%d -> ",ptr->data);
ptr = ptr->next;
}
}
int main() {
int data=0;
struct node *head;
head = malloc(sizeof(struct node));
if(head == NULL){
printf("Out of memory");
}
head->next = NULL;
while(data != -1){
printf("Enter a number to be added to the beginning of the list, -1 to exit.");
scanf("%d",&data);
if(data == -1)
break;
head = addToStart(head,data);
}
printf("Number have been recorded in the list. Here are the numbers");
displayList(head);
return 0;
}
列表被显示,但随后我看到了其他奇怪的数字。 IE 40274093。它的问题是什么。
I have my linked list that I created. I made addToStart function which has2 paramters, first parameter is the head of the list, second parameter is the data to be inserted in the nodes. I also have displayList which just displays the content in the list.
Code:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node* addToStart(struct node* head, int d){
struct node *new = malloc(sizeof(struct node));
if(new == NULL){
printf("out of memory");
}
else{
new->data = d;
new->next = NULL;
new->next = head;
head = new;
return head;
}
return 0;
}
void displayList(struct node* head){
struct node *ptr = head;
while(ptr != NULL){
printf("%d -> ",ptr->data);
ptr = ptr->next;
}
}
int main() {
int data=0;
struct node *head;
head = malloc(sizeof(struct node));
if(head == NULL){
printf("Out of memory");
}
head->next = NULL;
while(data != -1){
printf("Enter a number to be added to the beginning of the list, -1 to exit.");
scanf("%d",&data);
if(data == -1)
break;
head = addToStart(head,data);
}
printf("Number have been recorded in the list. Here are the numbers");
displayList(head);
return 0;
}
the list gets displayed but then I see other weird number(s). i.e 40274093. Whats the problem with it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您忘了初始化
head-&gt; data
。不过,您可以将其设置为null,而不是初始化它,然后立即开始调用
addtostart
。如果将null作为head
参数传递到addtostart
,则应将Next
设置为null并按预期工作。以下内容应解决您的问题:You forgot to initialize
head->data
.Instead of initializing it though, you can just set it to NULL, and immediatly start calling
addToStart
on it. If you pass NULL as thehead
parameter toaddToStart
, it should just set thenext
to NULL and work as expected. The following should fix your problem:清理一些内联评论:
Cleaned up with some inline comments: