【LeetCode & 剑指offer刷题】链表题2:6 从尾到头打印链表

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

6 从尾到头打印链表

题目描述

输入一个链表,从尾到头打印链表每个节点的值
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
//方法:利用栈的后进先出特性
//如果可以改变链表结构,则可以先反转链表指针,在遍历输出即可,可以不用辅助空间
class Solution
{
public :
    vector < int > printListFromTailToHead ( ListNode * head )
    {
        stack <ListNode*> nodes ;
        ListNode * p = head ;
       
        while ( p != nullptr )
        {
            nodes .push(p);
            p = p -> next ;
        }
       
        vector < int > result ;
        while (! nodes . empty ())
        {
            p = nodes.top();
            result . push_back ( p -> val );
            nodes . pop ();
        }
        return result ;
    }
};
 
 

猜你喜欢

转载自www.cnblogs.com/wikiwen/p/10225171.html