c中的链接字符串列表

时间:2015-06-07 23:30:08

标签: 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;
}
}

2 个答案:

答案 0 :(得分:2)

您永远不会将NULL设置为任何内容,它始终为tail。因此,您并未创建列表,而是创建一组未链接的浮动节点。

另一方面,don't cast the result of malloc

在另一个注释中,不需要遍历每个插入的整个列表 - 您可以将<ul class="paginate"> <li class="first active">1</li> <li><a href="#" data-page="2" title="Page 2">2</a></li> ...... </ul> 指针与头部一起保留,因此在没有循环的情况下添加到结尾。

答案 1 :(得分:1)

void insert(char str) {
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    temp->data = str;
    temp->next = NULL;

    if(head){//head != NULL
        struct node* temp1 = head;
        while(temp1->next != NULL) {//search last element
            temp1 = temp1->next;
        }
        temp1->next = temp;//insert new node
    } else {
        head = temp;//if head == NULL then replace with new node
    }
}
相关问题