题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
1)递归
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):
if listNode is None:
return []
else:
return self.printListFromTailToHead(listNode.next) + [listNode.val]
if __name__ == '__main__':
s = Solution()
l = list(map(int, input().strip().split()))
listNode = ListNode(l[0])
cur = listNode
for i in range(1, len(l)):
cur.next = ListNode(l[i])
cur = cur.next
cur.next = None
print(s.printListFromTailToHead(listNode))
c++:
// 递归
class Solution {
public:
vector<int> res;
vector<int> printListFromTailToHead(ListNode* head) {
if(head != NULL){
if(head->next != NULL){
printListFromTailToHead(head->next);
}
res.push_back(head->val);
}
return res;
}
};
2)栈的思想
python:
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
if listNode is None:
return []
else:
stack = []
res = []
while listNode is not None:
stack.append(listNode.val)
listNode = listNode.next
while len(stack) > 0:
res.append(stack.pop())
return res
c++:
// 栈
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
stack<int> stk;
while(head != NULL){
stk.push(head->val);
head = head->next;
}
while(!stk.empty()){
res.push_back(stk.top());
stk.pop();
}
return res;
}
};
3)数组反转
python:
# 数组反转
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
if listNode is None:
return []
else:
res = []
while listNode:
res.append(listNode.val)
listNode = listNode.next
i, j = 0, len(res) - 1
while i < j:
res[i], res[j] = res[j], res[i]
i += 1
j -= 1
return res
c++:
//数组反转
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
while(head != NULL){
res.push_back(head->val);
head = head->next;
}
int temp = 0;
int i=0,j=res.size()-1;
// 数组反转
while(i<j){
temp = res[i];
res[i]=res[j];
res[j]=temp;
i++;
j--;
}
return res;
}
};