剑指offer之反向打印链表值
生活随笔
收集整理的這篇文章主要介紹了
剑指offer之反向打印链表值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1?問題
反向打印鏈表值
?
?
?
?
2?思考
1)?我們利用棧的思想,新進后出,把鏈表的每個元素分別入棧之后再打印棧
2)既然上面用到了棧,我們應該就會想到用到遞歸來實現
?
?
?
?
3?代碼實現
#include <iostream> #include <stack> #include <stdlib.h>using namespace std;typedef struct node {int value;struct node *next; } Node;/***把鏈表的每一個元素遍歷出來放進棧,然后利用*棧把先進后出的特點,然后打印棧*/ void reverse_printf(Node *head) {if (head == NULL){std::cout << "head is NULL" << std::endl;return; }Node *p = head;stack<Node *> stk; while (p != NULL){stk.push(p);p = p->next;}while(!stk.empty()){Node *node = stk.top();std::cout << node->value << std::endl;stk.pop();} }/***既然上面用到了棧,那么我們自然而然就會想到*用遞歸的思想,我們就自己調用自己直到遍歷到最后*很明顯我們遞歸的條件是最后一個原始的next不能為空*/ void reverse_printf1(Node *head) {/**這樣也行if (head == NULL){return; }reverse_printf1(head->next);std::cout << head->value << std::endl;**/if (head != NULL){reverse_printf1(head->next);std::cout << head->value << std::endl;} }void printf(Node *head) {if (head == NULL){std::cout << "head is NULL" << std::endl;return; }Node *p = head;while (p != NULL){std::cout << p->value << std::endl;p = p->next;} }int main() {Node *head = NULL;Node *node1 = NULL;Node *node2 = NULL;Node *node3 = NULL;head = (struct node*)malloc(sizeof(Node));node1 = (struct node*)malloc(sizeof(Node));node2 = (struct node*)malloc(sizeof(Node));node3 = (struct node*)malloc(sizeof(Node)); if (head == NULL || node1 == NULL || node2 == NULL || node3 == NULL){std::cout << "malloc fail" << std::endl;return -1;}head->value = 0;head->next = node1;node1->value = 1;node1->next = node2;node2->value = 2;node2->next = node3;node3->value = 3;node3->next = NULL;printf(head);std::cout << "***************" << std::endl;reverse_printf(head);std::cout << "***************" << std::endl;reverse_printf1(head);free(head);free(node1);free(node2);free(node3);return 0;}?
?
?
?
4?運行結果
0 1 2 3 *************** 3 2 1 0 *************** 3 2 1 0?
總結
以上是生活随笔為你收集整理的剑指offer之反向打印链表值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指offer之把字符串里面空格替换成百
- 下一篇: 剑指offer之打印链表的倒数第N个节点