您的位置:首页 > 其它

5-从尾到头打印链表

2015-07-25 21:45 417 查看
题目描述:http://ac.jobdu.com/problem.php?pid=1511

输入一个链表,从尾到头打印链表每个节点的值。

输入:

每个输入文件仅包含一组测试样例。

每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点。第一行是链表第一个节点的值,依次类推。当输入到-1时代表链表输入完毕。-1本身不属于链表。

输出:

对应每个测试案例,以从尾到头的顺序输出链表每个节点的值,每个值占一行。

逆序打印链表,我们遍历链表只能从头到尾,现在要求我们从尾到头。后进先出,可以想到用栈存储遍历的节点,然后打印出栈序列。

递归的本质就是栈结构,在打印本节点之前,先打印本节点的下一个节点

#include <iostream>
#include <stack>
using namespace std;
class Node {
public:
int val;
Node* next;
Node(int val, Node* next = NULL) {
this->val = val;
this->next = next;
}
};
// 递归实现
void PrintListReversingRecur(Node* head) {
if (head == NULL)
return;
PrintListReversingRecur(head->next);
cout << head->val << " ";
}
// 栈实现
void PrintListReversingStack(Node* head) {
stack<Node*> s;
while (head != NULL) {
s.push(head);
head = head->next;
}
while (s.empty() == false) {
cout << s.top()->val << " ";
s.pop();
}
cout << endl;
}
int main() {
Node* head = new Node(1, new Node(2, new Node(3, new Node(4, NULL))));
for (Node* iter = head; iter != NULL; iter = iter->next)
cout << iter->val << " ";
cout << endl;
cout << "逆序打印" << endl;
PrintListReversingRecur(head);
cout << endl;
PrintListReversingStack(head);
}


输出结果:
1 2 3 4
逆序打印
4 3 2 1
4 3 2 1
[Finished in 0.4s]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: