#include <stdio.h>
#include <stdlib.h>
typedef struct List {
int val;
struct List *next;
}List;
void InitList(List **h, List **t)
{
*h = (List *)malloc(sizeof(List));//*h就是头指针的地址
*t = (List *)malloc(sizeof(List));//*t就是尾指针的地址
if(!(*h) || !(*t)) exit(-1);
(*h)->next = *t;
(*t)->next = NULL;
printf("初始化成功\n");
}
List *CreateList(List *h)
{
int input;
while(~scanf("%d", &input)) {
List *p = (List *)malloc(sizeof(List));
if(!p) exit(-1);
p->val = input;
p->next = h->next;
h->next = p;
}
printf("创建成功\n");
return h;
}
void PrintList(List *h)
{
List *p = h->next;
while(p) {
if(p->next) printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
void ClearList(List *h)
{
List *p = NULL;
while(h) {
p = h;
h = h->next;
free(p);
}
printf("清空完毕\n");
}
void InvertList(List *f, List *p)
{
if(p->next) InvertList(p, p->next);
p->next = f;
}
int main()
{
List *head = NULL, *tail = NULL;
InitList(&head, &tail);//传入指针的地址,这是一个二级指针
printf("逆序输入数据,以EOF结束标志\n");
head = CreateList(head);//输入数据创造一个带头带尾的链表
PrintList(head);
InvertList(NULL, head);//递归倒置
printf("逆置成功\n");
PrintList(tail);//尾指针变成了头指针
ClearList(tail);
return 0;
}
时间: 2024-11-05 14:36:56