从头到尾打印链表

来源:互联网 发布:云南省建设厅官网通知 编辑:程序博客网 时间:2024/06/08 19:54

题目描述

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

思路1:用的方式(C++)

/***  struct ListNode {*        int val;*        struct ListNode *next;*        ListNode(int x) :*              val(x), next(NULL) {*        }*  };*/class Solution {public:    vector<int> printListFromTailToHead(ListNode* head) {        stack<int>temp;//初始化一个栈        vector<int>res;//初始化一个容器        while(head){ //当链表不为空            temp.push(head->val); //入栈            head = head->next;        }        while(temp.size()){   //栈不为空            res.push_back(temp.top());  //从栈顶拿出值            temp.pop();  //出栈        }        return res;    }};
思路2:递归实现(C++)

class Solution {public:    vector<int> printListFromTailToHead(ListNode* head) {        vector<int>res;        if(head != NULL){            res = printListFromTailToHead(head->next);            res.push_back(head->val);        }        return res;    }};









原创粉丝点击