剑指offer.从未到头打印链表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Wilder_ting/article/details/88904658

剑指offer.从未到头打印链表

输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。返回的结果用数组存储。

样例
输入:[2, 3, 5]
返回:[5, 3, 2]

1、使用栈。

class Solution {
public:
    vector<int> printListReversingly(ListNode* head) {
        stack<int> result;
        while(head){
            result.push(head->val);
            head = head->next;
        }
        vector<int> res;
        while(!result.empty()){
            res.push_back(result.top());
            result.pop();
        }
        return res;
    }
};

2、不使用栈

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> printListReversingly(ListNode* head) {
        vector<int> result;
        while(head){
            result.push_back(head->val);
            head = head->next;
        }
        return vector<int>(result.rbegin(),result.rend());
    }
};

3、链表反转,然后使用数组存储

class Solution {
public:
    vector<int> printListReversingly(ListNode* head) {
        vector<int> result;
        if(head == NULL){
            return result;
        }
        
        ListNode* p = head->next;
        head->next = NULL;
        while(p != NULL){
            ListNode* tmp =p->next;
            p->next = head;
            head = p;
            p = tmp;
        }
  
  while(head){
      result.push_back(head->val);
      head = head->next;
  }
  return result;
    }
};
posted @ 2019-03-29 21:29 Tingwei_chen 阅读( ...) 评论( ...) 编辑 收藏

猜你喜欢

转载自blog.csdn.net/Wilder_ting/article/details/88904658