Print linked list using recursion【1月17日学习笔记】

点击查看代码
//Print linked list using recursion
#include<iostream>
using namespace std;
struct node {
	int data;
	node* next;
};


void print(node* p) {
	if (p == NULL)  return;//递归中止条件
	cout << p->data << " ";
	print(p->next);
}

void reverseprint(node* p) {
	if (p == NULL)  return;
	reverseprint(p->next);//先递归
	cout << p->data << " ";
}


node* insert(int x,node* A) {
	node* temp = new node;
	temp->data = x;
	temp->next = NULL;

	if (A == NULL) {
		A = temp;
	}//头指针为空时要建立globle区与heap区的link才能通过头指针索引
	else {
		node* run = A;
		while (run->next != NULL) {
			run = run->next;
		}
		run->next = temp;
	}//头指针不为空时用遍历指针索引
	return A;
}


int main() {
	node* A = NULL;//局部头指针
	A = insert(2, A);
	A = insert(4, A);
	A = insert(6, A);
	A = insert(5, A);
	print(A); cout << endl;
	reverseprint(A);
}
posted @ 2024-01-17 16:18  bituion  阅读(12)  评论(0)    收藏  举报