作者在 2020-03-19 18:51:31 发布以下内容
#include<stdio.h>
#include<stdlib.h>
/*注意:当输入数据为-1时退出输入操作*/
typedef int DataType; //定义单链表的数据类型为整型
struct Node
{
DataType data; //数据域
struct Node* next; //指针域
};
typedef struct Node *PNode; //定义指向结构体的PNode类型
typedef struct Node *LinkList; //定义链表类型
LinkList SetNullList_Link() //创建带有头结点的空链表
{
LinkList head = (LinkList)malloc(sizeof(struct Node));
if (head != NULL) head->next = NULL;
else printf("alloc failure");
return head; //返回头指针
}
void CreateList_Tail(struct Node* head)// 尾插法建立单链表
{
PNode p = NULL;
PNode q = head;
DataType data;
scanf("%d", &data);
while (data != -1)
{ //分配空间,赋值
p = (struct Node*)malloc(sizeof(struct Node));
p->data = data;
p->next = NULL;
q->next = p;
q = p;
scanf("%d", &data);
}
}
void print(LinkList head) //垂直输出单链表
{
PNode p = head->next;
while (p)
{
printf("%d\n", p->data);
p = p->next;
}
printf("\n");
}
void DestoryList_Link(LinkList head) //释放单链表
{
PNode pre = head;
PNode p = pre->next;
while (p)
{
free(pre);
pre = p;
p = pre->next;
}
free(pre);
}
void reverse(LinkList H) //原地制逆
{
PNode p,q;
PNode pre = H;
//定义指针
p=pre->next; //p获取链表数据
pre->next=NULL;
//若p不为空进入循环
while(p)
{
//指针后移
q=p; //q获取p的数据
p=p->next;
//改为头插法
q->next=pre->next;
pre->next=q;
}
//在这里填入你的代码
}
int main()
{
//声明链表头指针
LinkList head = NULL;
head = SetNullList_Link();
CreateList_Tail(head);//尾插法建表
reverse(head);//原地制逆算法: 尾插法插入,顺序取出,头插法插入
print(head);//输出单链表
DestoryList_Link(head);
return 0;
}