本篇,先建立一个静态的单链表。
然后演示用递归的方法打印单链表的内容。
#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;
}