首页 > 代码库 > 从尾到头打印链表

从尾到头打印链表

使用数据结构stack或者递归

1 使用stack

#include <iostream>
#include <stack>
using namespace std;

 typedef struct listNode{
	int key;
	struct	listNode *pNext;
 } * pNode,Node;

void createNode(pNode &pHead){
		bool isFirst=true;
		int temp;
		scanf("%d",&temp);
		pNode p=pHead,q;
		while(temp!=0){
			q=(pNode)malloc(sizeof(Node));
			q->key=temp;
			q->pNext=NULL;
			if(isFirst){
				p=pHead=q;
				isFirst=false;
			}else{
				p->pNext=q;
				p=q;
			}

			scanf("%d",&temp);
		}
		cout<<"原链表是:"<<endl;
		p=pHead;
		while(p){
			cout<<p->key<<" ";
			p=p->pNext;
		}
}

void printListReverse(const pNode pHead){
	stack<pNode> veP;
	pNode p=pHead;
	while(p){
		veP.push(p);
		p=p->pNext;
	}
	while(!veP.empty()){
		p=veP.top();
		cout<<p->key;
		veP.pop();
	}

}

int main(){
	pNode pHead=NULL;
	createNode(pHead);
	printListReverse(pHead);
	return 0;

}

运行结果:


2 递归

#include <iostream>
#include <stack>
using namespace std;

 typedef struct listNode{
	int key;
	struct	listNode *pNext;
 } * pNode,Node;

void createNode(pNode &pHead){
		bool isFirst=true;
		int temp;
		scanf("%d",&temp);
		pNode p=pHead,q;
		while(temp!=0){
			q=(pNode)malloc(sizeof(Node));
			q->key=temp;
			q->pNext=NULL;
			if(isFirst){
				p=pHead=q;
				isFirst=false;
			}else{
				p->pNext=q;
				p=q;
			}

			scanf("%d",&temp);
		}
		cout<<"原链表是:"<<endl;
		p=pHead;
		while(p){
			cout<<p->key<<" ";
			p=p->pNext;
		}
}

void printListReverse(const pNode pHead){
	if(pHead==NULL)
		return;
	printListReverse(pHead->pNext);
	cout<<pHead->key;

}

int main(){
	pNode pHead=NULL;
	createNode(pHead);
	printListReverse(pHead);
	return 0;

}

运行结果: