#include<stdio.h>
#include<stdlib.h>
struct link {
int data;
struct link *next;
};
//新建一个节点添加到链表末尾,并返回头指针
struct link* appendNode(struct link *head)
{
struct link *p = NULL;
struct link *pr = head;
p = (struct link *)malloc(sizeof(struct link));
if (p == NULL)
{
printf("内存申请失败!");
exit(0);
}
else if (pr->next == NULL)//链表为空
{
pr->next = p;
p->next = NULL;
}
else//链表不空
{
while (pr->next!=NULL)
{
pr = pr->next;
}
pr->next = p;
p->next = NULL;
}
printf("输入链表数据:");
scanf_s("%d",&(p->data));
return head;
}
//遍历节点
void printLink(struct link*head)
{
printf("链表的数据为:");
struct link *p = head->next;
if (p == NULL)
{
printf("这是一个空链表!");
}
else {
while (p != NULL)
{
printf("%5d", p->data);
p = p->next;
}
}
}
//链表节点空间释放
void Destroy(struct link*head)
{
struct link *p = head->next;
struct link *pr = NULL;
while (p!= NULL)
{
pr = p;
p = p->next;
free(pr);
}
}
int main() {
char c;
struct link *head=NULL;
head = (struct link*)malloc(sizeof(struct link));
head->next = NULL;
printf("你想添加新节点吗?(Y/N)");
scanf_s("%c", &c);
while(c=='y'||c=='Y')
{
head = appendNode(head);
printf("你想添加新节点吗?(Y/N)");
getchar();
scanf_s("%c", &c);
}
printLink(head);
Destroy(head);
}