双向链表的创建与顺,逆序的输出问题
程序代码:
/* 程序名:双向链表的创建与输出 作者:Yucoat */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define SIZE 20 #define MALLOCMEMORY (SqList *)malloc(sizeof(SqList)) typedef struct SqList SqList; struct SqList { char name[SIZE]; SqList *last; SqList *next; }; //初始化链表 SqList *InitSqList(SqList *h, SqList *t); //输出链表 void ShowSqList(SqList *h); int main() { SqList *head = NULL, *tail = NULL; head = InitSqList(head, tail); ShowSqList(head); //顺序输出链表 ShowSqList(tail); //逆序输出链表 return 0; } SqList *InitSqList(SqList *h,SqList *t) { SqList *p1 = NULL, *p2 = NULL; char temp[SIZE]; p1 = p2 = MALLOCMEMORY; printf("请输入名字:"); scanf("%s", p2->name); p2->last = NULL; p2->next = NULL; t = p2; //尾指针指向p2 while (1) { if (h == NULL) //如果链表为空,接表头 { h = p2; } else //如果链表不为空,接表尾 { t = p2; } printf("请输入名字:"); scanf("%s", temp); if (temp[0] != '#') //如果输入的字符串以#开头,结束 { p2 = p1->next; p2 = MALLOCMEMORY; strcpy(p2->name, temp); p2->last = p1; p2->next = NULL; p1 = p1->next; } else { break; } } return h; } void ShowSqList(SqList *h) { SqList *temp = h; while (temp->next != NULL) { printf("%s", temp->name); temp = temp->next; } }
================================
错得很明显。,在执行的时候,输出到第三个名字的时候就出错了!
不知道怎么改,求高手给力!