简单c语言 递归 逆转 链表

#include<stdio.h>
#include<stdlib.h>
typedef struct Node{ 
    int data; 
    struct Node* next; 
}node;

node* create(int n)//假设有n个节点
{
	node* p = NULL;
	node* head =NULL; 
	int i = 1; 
    while(i <= n)
	{ 
	    if(!head){
  		    head = p =(node*)malloc(sizeof(struct Node)); 
            printf("p->data=\t");
            scanf("%d",&p->data);//赋值 
			p->next = NULL; 
    	}else{	
            p->next = (node*)malloc(sizeof(struct Node));
            printf("p->data=\t");
            scanf("%d",&p->next->data);//赋值 
            p->next->next = NULL;
            p = p->next;
	    }
    	++i;
	} 
    return head; 
}

node* reverse(node* p)//利用递归方法解决逆转 
{ 
	node* p1;
	if(!p){
		return NULL;
	}else{
		if(p->next != NULL){
		p1 = reverse(p->next);//不断调用返回逆转后的节点 
		p->next->next = p; //逆转 
		p->next = NULL; // 善后 
		return p1; 
	    }else{
		      return p;
	    } 
	} 
}
 
int main()
{
	int n;
	printf("请输入您需要输入几个元素:\t"); 
	scanf("%d",&n);
	node* p = create(n); 
    node* y = reverse(p);
    printf("------------------------------------\n");
    while(y!=NULL){
    	printf("y->data=%9d\n",y->data);
    	y=y->next;
    } 
} 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值