您的位置:首页 > Web前端

剑指offer系列源码-从尾到头打印链表

2014-12-04 14:59 525 查看
ob地址

题目描述:
输入一个链表,从尾到头打印链表每个节点的值。
输入:
每个输入文件仅包含一组测试样例。
每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点。第一行是链表第一个节点的值,依次类推。当输入到-1时代表链表输入完毕。-1本身不属于链表。
输出:
对应每个测试案例,以从尾到头的顺序输出链表每个节点的值,每个值占一行。
样例输入:
1
2
3
4
5
-1
样例输出:
5
4
3
2
1
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;

struct ListNode{
int value;
ListNode * next;
};

void reversePrint(ListNode * pHead){
if(pHead==NULL){
return;
}
std::stack<ListNode*> nodes;

while(pHead!=NULL){
nodes.push(pHead);
pHead = pHead->next;
}
while(!nodes.empty()){
ListNode* top = nodes.top();
printf("%d\n",top->value);
nodes.pop();
}
}

int main(){
int value;
ListNode * pHead =NULL;int i=0;
ListNode* pCur = pHead;
while(scanf("%d",&value)&&value!=-1){
//addToTail(pHead,n);
ListNode* pNew = new ListNode();
pNew->value = value;
pNew->next = NULL;
if(i==0){
pHead = pNew;
pCur = pHead;
}else{
pCur->next = pNew;
pCur = pCur->next;
}
i++;
}
reversePrint(pHead);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: