当前位置: 首页 > 工具软件 > ILLA > 使用案例 >

2.6-12对于不带头结点的单链表 L,设计一个递归算法逆序输出所有结点值

连德水
2023-12-01
#include "LinkList.cpp"
#include <bits/stdc++.h>

void Revdisp(LinkNode *L) {  // 逆序输出 
	
	if(L == NULL)
		return ;
	else{
		Revdisp(L->next);
		cout <<" " << L->data;
	}

}

int main() {
	int a[] = {1,2,5,2,3,2};
	LinkNode *L,*p;
	int n = sizeof(a) / sizeof(a[0]);
	L = CreateList(a,n);
	DispList(L);
	cout << endl;
	Revdisp(L);
	Release(L);
	return 0;
}
#include<bits/stdc++.h>

using namespace std;

typedef struct Node {
	int data;
	struct Node *next;
} LinkNode;

LinkNode *CreateList(int a[],int n) {
	if(n < 0)
		return NULL;
	LinkNode *head = (LinkNode *)malloc(sizeof(LinkNode));
	LinkNode *p = (LinkNode *)malloc(sizeof(LinkNode));
	p = head;
	head->data = a[0];
	int i = 0;
	for(i = 1; i < n; i++) {
	
		LinkNode *node = (LinkNode *)malloc(sizeof(LinkNode));
		node->data = a[i];
		p->next = node;
		p = node;
	}
	p->next = NULL;  // 尾结点next域置为空
	return head;
}

void DispList(LinkNode *ln) {
	cout << " "; 
	if(ln != NULL){
		cout << ln->data;
		DispList(ln->next);
	}
}

void Release(LinkNode *ln) {
	if(ln->next == NULL)
		return ;
	else {
		Release(ln->next);
		free(ln);
	}
}
 类似资料: