您的位置:首页 > 其它

递归逆序打印单链表(c实现)

2015-01-05 22:55 239 查看
递归逆序打印单链表。交换打印语句和递归调用的顺序,可以实现顺序打印和逆序打印链表。

#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
	int data;
	struct Node *next;
}Node ;
Node *create_list(int *arr,const int len)
{
	if(arr==NULL||len<=0)
	{
		return NULL;
	}
	Node *head = (Node*)malloc(sizeof(Node));
	head->data = arr[0];
	Node *p,*q = head;
	for(int i=1;i<len;i++)
	{
		p = (Node*)malloc(sizeof(Node));
		p->data = arr[i];
		q->next = p;
		q = p;
	}
	q->next = NULL;
	return head;
}
void rprint(Node *head)
{
	if(head==NULL)
	{
		return ;
	} else {
		rprint(head->next);
		printf("%d ",head->data);
	}
}
void print(Node *head)
{
	Node *p = head;
	while(p!=NULL)
	{
		fprintf(stdout,"%d ",p->data);
		p = p->next;
	}
}
int main(void)
{
	int a[] = {1,2,3,4,5,6,7,8,9};
	const int len = sizeof(a)/sizeof(int);
	Node *head = create_list(a,len);
	print(head);
	printf("\n");
	rprint(head);
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: