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

3从尾到头打印链表

时间:2017-11-23 08:08:47      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:subject   public   res   pre   desc   result   使用   bsp   oid   

题目描述

输入一个链表,从尾到头打印链表每个节点的值。
 
思路:反过来的方法使用stack就可以,或者使用递归方法实现。
链表指向下一个使用next指针,不要直接使用++pointer的操作。因为链表不一定是连续存储的。
1.stack
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> result;
        if(head == nullptr){
            return result;
        }
        stack<int> s;
        ListNode* pHead = head;
        while(pHead != nullptr){
            s.push(pHead -> val);
            pHead = pHead -> next;
        }
        int sz = s.size();
        for(int i = 0;i < sz;++i){
            result.push_back(s.top());
            s.pop();
        }
        return result;
    }
};

2、递归

class Solution {
public:
    void helper(ListNode* head,vector<int> &result){
        if(head == nullptr){
            return;
        }
         
        helper(head -> next,result);
        result.push_back(head -> val);//一定要把位置放在这里
    }
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> result;
        if(head == nullptr){
            return result;
        }
        helper(head,result);
        return result;
    }
};

 

3从尾到头打印链表

标签:subject   public   res   pre   desc   result   使用   bsp   oid   

原文地址:http://www.cnblogs.com/dingxiaoqiang/p/7881341.html

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