C语言实现单链表的逆置-实训

任务描述

本关需要你设计一个程序,实现单链表的逆置。

相关知识
单链表的逆置分为两种方法:头插法和就地逆置法,这两种方法虽然都能够达到逆置的效果,但还是有着不小的差别。

编程要求
按程序提示输入并创建一个单链表,带有头结点;

可自定义链表的长度,可自定义链表储存的数据类型,注意更改相应的输入输出方式;

实现单链表的逆置,直观地输出结果。

效果如下:
输入:

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!

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值