3.从尾到头打印链表

题目

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

思路一

  • 遍历链表,每个节点的值存到数组中。
  • 将数组中的元素反转。

代码

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        if ( head == nullptr ) return res;
         
        while ( head != nullptr ) {
            res.push_back( head->val );
            head = head->next;
        }
         
        int start = 0, end = res.size() - 1;
        while ( start < end ) {
            int tmp = res[start];
            res[start] = res[end];
            res[end] = tmp;
             
            ++start;
            --end;
        }
         
        return res;
    }
};

思路二

  • 遍历链表,将链表的节点保存到栈中。
  • 栈吐出结点直到为空,依次将节点的值保存到数组中。
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        if ( head == nullptr ) return res;
         
        stack<ListNode*> s;
        while ( head != nullptr ) {
            s.push( head );
            head = head->next;
        }
         
        ListNode* node = nullptr;
        while ( !s.empty() ) {
            node = s.top();
            s.pop();
            res.push_back( node->val );
        }
         
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值