#include<stdio.h>
#include<stdlib.h>
struct demo
{
char str[15];
struct damo* pnext;
};
struct demo* create()
{
struct demo* pnew,*pend,*phead;
pnew=pend=(struct demo*)malloc(sizeof(struct demo));
phead=pnew;
printf("请输入文字");
scanf("%s",phead->str);
if(*(phead->str)!="\n");
{
for(;;)
{
pnew=(struct demo*)malloc(sizeof(struct demo));
pend->pnext=pnew;
printf("请输入文字");
scanf("%s",pnew->str);
if(*(pend->str)=="\n")
{
break;
}
pend=pnew;
}
}
pend->pnext=NULL;
return phead;
}
void main()
{
struct demo* phead;
struct demo* pprint;
phead=create();
printf("\n输出为:\n");
pprint=phead;
printf("%s",*(pprint->str));
for(;;)
{
pprint=pprint->pnext;
printf("%s",*(pprint->str));
if(pprint==NULL)
{
break;
}
}
}
链表可以正常输入,但是当输入回车退出输入的循环后,就无法正常输出了,求解答,谢谢
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct demo
{
char str[15];
struct demo *next;
};
struct demo *create()
{
struct demo *head = NULL;
struct demo *tail = NULL;
char buffer[15];
while (scanf("%s", buffer) == 1) // Read input till EOF (i.e. Ctrl+D (Linux) / Ctrl+Z (Windows))
{
struct demo *p = (struct demo *)malloc(sizeof(struct demo));
strcpy(p->str, buffer);
p->next = NULL;
if (!head)
head = p;
if (tail)
tail->next = p;
tail = p;
}
return head;
}
void print(struct demo *head)
{
while (head)
{
printf("%s\n", head->str);
head = head->next;
}
}
void destroy(struct demo *head)
{
while (head)
{
struct demo *p = head;
head = head->next;
free(p);
}
}
int main()
{
struct demo *head = create();
print(head);
destroy(head);
}