知识点:单向链表、栈
一、题目描述:输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
二、解题思路:
思路1:先按正序的顺序遍历链表并将链表节点数据加入到数组vector中;然后利用C++中vector的反向迭代器实现数组逆序。
代码实现:
C++:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
//1、
ListNode *p;//定义结构体类型的指针,并指向头节点,用于遍历链表
p = head;
vector<int> array;
while(p != NULL){
array.push_back(p->val);
p = p->next;
}
//通过while循环已经将链表节点数据域中存储的值按正序存到了数组array中
//2
reverse(array.begin(),array.end());
return array;
//return vector<int> (array.rbegin(),array.rend());//vector类型的容器才有反向迭代器
}
};
python实现:类似c++中vector容器有反向迭代器,python中有切片可以直接实现列表的逆序。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):#listNode是个链表头
# write code here
res = [] #返回变量
while listNode:
res.append(listNode.val)
listNode = listNode.next
#list.[::-1]直接实现list的逆序
return res[::-1] #返回res的逆序
思路2:借助栈先入后出的特性,将链表节点先入栈后出栈,再压入序列中
代码实现:
C++:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
//1、遍历链表,将链表节点数据压入栈
stack<int> s;//创建栈
ListNode* p = head;//定义用于遍历链表的指针,初始化指向头节点
while(p != NULL){
s.push(p->val);//栈中是push不是push_back
p = p->next;
}
//2、出栈,依次将栈顶元素存入vector数组中
vector<int>array;
p = head;//遍历完链表,指针p指向链表尾节点后面的NULL
while(p != NULL){//其实是遍历栈
array.push_back(s.top());
s.pop();
p = p->next;
}
return array;
}
};