⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 list.cpp

📁 C++的电子教程
💻 CPP
字号:
//程序实例6_2
//用递归实现链表的创建和输出

#include <stdio.h>
#include <stdlib.h>

//链表结构声明
struct list
{
	int data;           //结点数据
	struct list *next;   //指向下一结点
};
typedef struct list Node ;   //定义结点类型


//递归链表输出函数
void print_list(Node *head)
{
	if (head!=NULL)
	{
		printf("[%d]",head->data);       //输出结点数据
		print_list(head->next);          //递归调用
	}
}

//递归链表创建函数
Node *create_list(int *array,int len ,int pos)
{
	Node *head;

	if (pos==len)
		return NULL;             //终止条件
	else
	{
		head=(Node *)malloc(sizeof(Node));
		if (!head)
			return NULL;
		head->data=array[pos];     //结点赋值
		head->next=create_list(array,len,pos+1); //递归调用
		return head;
	}
}


//主函数
void main()
{
	int  list[6]={1,2,3,4,5,6}; 
	Node *head;

	head=create_list(list,6,0);     //创建链表
	if (!head)
	{
		printf("内存分配失败!\n");
		exit(1);
	}
	printf("链表的内容:\n");
	print_list(head);
	printf("\n");
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -