JZ-C-05

來源:互聯網
上載者:User

標籤:

劍指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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.