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

JZ-C-05

时间:2016-05-17 19:14:25      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

剑指offer第五题:从尾到头打印链表:利用栈的‘后进先出’/递归

 1 //============================================================================
 2 // Name        : JZ-C-05.cpp
 3 // Author      : Laughing_Lz
 4 // Version     :
 5 // Copyright   : All Right Reserved
 6 // Description : Hello World in C++, Ansi-style
 7 //============================================================================
 8 
 9 #include <iostream>
10 #include <iomanip>
11 #include <stack>
12 #include  <list>
13 using namespace std;
14 
15 typedef struct SNode {
16     int data;
17     struct SNode *next;
18 } NODE;
19 
20 /*从尾到头打印链表:递归*/
21 void PrintListReverse1(NODE * head) {
22     if (head != NULL) {
23         if (head->next != NULL) {
24             PrintListReverse1(head->next); //递归
25         }
26         cout << head->data << setw(3);
27     }
28 }
29 /*从尾到头打印链表:利用栈的后进先出特点*/
30 void PrintListReverse2(NODE *head) {
31     std::stack<NODE*> nodes; //创建一个栈,存入NODE*类型的元素
32     NODE *p = head;
33     while (p != NULL) {
34         nodes.push(p); //压入栈中
35         p = p->next;
36     }
37     while (!nodes.empty()) {
38         cout <<nodes.top()->data << setw(3); //‘后进先出‘出栈
39         nodes.pop();
40     }
41 }
42 /*建立一个单链表*/
43 NODE* CreatList() {
44     NODE *node1 = new NODE();
45     NODE *node2 = new NODE();
46     NODE *node3 = new NODE();
47     NODE *node4 = new NODE();
48     NODE *node5 = new NODE();
49     node1->data = 1;
50     node2->data = 2;
51     node3->data = 3;
52     node4->data = 4;
53     node5->data = 5;
54     node1->next = node2;
55     node2->next = node3;
56     node3->next = node4;
57     node4->next = node5;
58     node5->next = NULL;
59     return node1;
60 }
61 int main() {
62     NODE *head = CreatList();
63 //    NODE *head = NULL;
64     PrintListReverse2(head);
65     return 0;
66 }

 

JZ-C-05

标签:

原文地址:http://www.cnblogs.com/Laughing-Lz/p/5502754.html

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