c - c中的链接字符串列表

标签 c linked-list

我正在尝试这个要求用户输入字符串的简单代码。当它接收到输入时,它会尝试将字符串的每个元素复制到链表中的不同位置。一切正常(我认为)但是当我打印链接列表时,屏幕没有显示任何输出。知道为什么会这样吗?

#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/

相关文章:

java - 为什么linkedlist.java不导出Node类

c - c中的可用内存问题删除了链表中的某些值

c - 这个结构定义到底是什么意思?

c - printf() 无格式字符串打印字符和整数数组 --> 垃圾

php - C 中的关联数组

c++ - DWMEnableBlurBehind 使我的界面控件半透明

c - 如何将全局寄存器变量关联到 %gs(或 %fs)?

模板的 C++ 链接错误,仅使用头文件,为什么?

java - 从为父类(super class)创建的链表中插入和提取子类

c - 存储 1 到 1000 素数的链表