只有刻意练习递归,才能掌握递归-递归专题11-递归法打印单链表

本篇,先建立一个静态的单链表。

然后演示用递归的方法打印单链表的内容。 

#include<stdio.h>
 
struct node
{
	int data;
	struct node *next;	
};
 
void printF2L(struct node *head)
{//head指向第一个数据结点 
//从头到尾打印,递归 
	struct node *p=head;
	if(p==0)return;
	printf("%d ",p->data);//先打印第一个 
	printF2L(p->next); //再打印其他		
}
void printL2F(struct node *head)
{//head指向第一个数据结点 
//从尾到头打印,递归 
	struct node *p=head;
	if(p==0)return;
	printL2F(p->next); //先打印其他 
	printf("%d ",p->data);//再打印第一个 
			
}
int main(void)
{
	struct node head, a,b,c,d,e;	
	
	a.data=1;a.next=0;
	b.data=2;b.next=0;
	c.data=3;c.next=0;
	d.data=4;d.next=0;
	e.data=5;e.next=0;	
	head.next=&a;
	a.next=&b;
	b.next=&c;
	c.next=&d;
	d.next=&e;	
	
	printF2L(head.next);
	printf("\n"); 
	printL2F(head.next);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43917370/article/details/106867814
今日推荐