我正在尝试这个要求用户输入字符串的简单代码。当它接收到输入时,它会尝试将字符串的每个元素复制到链表中的不同位置。一切正常(我认为)但是当我打印链接列表时,屏幕没有显示任何输出。知道为什么会这样吗?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node {
char data;
struct node* next;
};
struct node* head = NULL;
void insert(char);
void print();
void main() {
char str1[20];
int i;
printf("Enter the string\n");
fgets(str1,20,stdin);
int len = strlen(str1);
printf("%d\n",len);
for(i=0;i<len;i++) {
insert(str1[i]);
}
print();
}
void insert(char str) {
struct node* temp = (struct node*)malloc(sizeof(struct node));
struct node* temp1 = head;
while(temp1!=NULL) {
temp1 = temp1->next;
}
temp->data = str;
temp1 = temp;
}
void print() {
struct node *temp;
temp = head;
while(temp!=NULL) {
printf("%c ",temp->data);
temp = temp->next;
}
}
最佳答案
您永远不会将 head
设置为任何内容,它将始终为 NULL
。因此,您创建的不是列表,而是一组未链接的 float 节点。
另一方面,don't cast the result of malloc
还有一点需要注意,每次插入都无需遍历整个列表 - 您可以将 tail
指针与头部一起保留,因此无需循环即可完成添加到末尾的操作。
关于c - c中的链接字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30699519/