任务描述
本关需要你设计一个程序,实现单链表的逆置。
相关知识
单链表的逆置分为两种方法:头插法和就地逆置法,这两种方法虽然都能够达到逆置的效果,但还是有着不小的差别。
编程要求
按程序提示输入并创建一个单链表,带有头结点;
可自定义链表的长度,可自定义链表储存的数据类型,注意更改相应的输入输出方式;
实现单链表的逆置,直观地输出结果。
效果如下:
输入:
6
1 212 7 8 0 2
输出:
链表逆置前的数据:
1 212 7 8 0 2
链表逆置后的数据:
2 0 8 7 212 1
代码如下
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct node {
int data;
struct node *next;
}Node;
Node * CreatList()//创建链表头
{
Node *phead = (Node *)malloc(sizeof(Node));
phead->next=NULL;
return phead;
}
Node * CreatNode(Node * phead,int n)//创建新节点,n表示创建节点个数
{
while(n--){
Node * newPoint = (Node *)malloc(sizeof(Node));//创建一个新节点
if(newPoint == 0)
{
printf("内存分配错误\n");
break;
}
scanf("%d", &newPoint->data);
phead->next = newPoint;
phead = newPoint;
}
phead -> next = NULL;
return 0;
}
void ShowList(struct node * headNode)//打印链表
{
struct node * pMove = headNode ->next;
while(pMove)
{
printf("%d ",pMove->data);
pMove=pMove->next;
}
}
void ShowList2(struct node * headNode,int n)
//附加打印链表,这里是为了保证逆置以后输出的位置不偏移
{
struct node * pMove = headNode;
while(pMove != NULL && n--)
{
printf("%d ",pMove->data);
pMove=pMove->next;
}
}
Node* ReverseList(Node *head) //逆置单链表
{
Node *newHead;
if(head==NULL||head->next==NULL)
return head;
newHead=ReverseList(head->next);
head->next->next=head;
head->next=NULL;
return newHead;
}
/********** End **********/
int main(void)
{
int n;
scanf("%d",&n);
Node *phead;
phead = CreatList();
CreatNode(phead,n);
printf("链表逆置前的数据:\n");
ShowList(phead);
phead = ReverseList(phead);
printf("\n链表逆置后的数据:\n");
ShowList2(phead,n);
return 0;
}
学会将列表功能模块化,各司其职,实用性up!