简单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;
    } 
} 

猜你喜欢

转载自blog.csdn.net/qq_52001969/article/details/112911531