码迷,mamicode.com
首页 > 其他好文 > 详细

从尾到头打印链表

时间:2014-07-30 17:30:34      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:从尾到头打印链表

使用数据结构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;

}

运行结果:

bubuko.com,布布扣

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;

}

运行结果:

bubuko.com,布布扣

从尾到头打印链表,布布扣,bubuko.com

从尾到头打印链表

标签:从尾到头打印链表

原文地址:http://blog.csdn.net/buyingfei8888/article/details/38302959

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!