题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
示例1
输入
复制
{67,0,24,58}
返回值
复制
[58,24,0,67]
java
解法1:可以利用堆栈的"先进后出的"特性进行操作,链表是链式结构,结点和结点的关联不是线性的,因此无法通过下标的形式进行遍历,只能通过内部的next进行下一个结点的访问。
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
//即使链表首节点为空,也应该返回元素为空的数组链表对象
ArrayList<Integer> target = new ArrayList<>();
if (null == listNode) {
return target;
}
//首先获取所有的结点中存储的元素,并将其存入先进后出的栈中
Stack<Integer> stack = new Stack<>();
while (null != listNode) {
stack.push(listNode.val);
listNode = listNode.next;
}
//出栈并将其存入到ArrayList中
while (!stack.isEmpty()) {
target.add(stack.pop());
}
return target;
}
}
解法2:本题是想要从尾部打印链表,隐含的意思是进行链表翻转和翻转后的链表打印。
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
//即使链表首节点为空,也应该返回元素为空的数组链表对象
ArrayList<Integer> target = new ArrayList<>();
if (null == listNode) {
return target;
}
ListNode pre = null;
ListNode next = listNode;
//next结点为空代表当前结点为空,那么pre为新的链表首节点
while (null != next) {
//next指向当前结点的下一个结点,并将当前结点的next指向上一个结点
next = listNode.next;
listNode.next = pre;
//完成上面的赋值操作,将pre指向当前结点,并将当前结点指向下一个结点
pre = listNode;
listNode = next;
}
while (null != pre) {
target.add(pre.val);
pre = pre.next;
}
return target;
}
}
c++
解法1:与java解法1类似
疑问:emplace_back是什么鬼,使用push_back进行赋值报错
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> stack;
vector<int> target;
while (NULL != head) {
stack.push(head->val);
head = head->next;
}
while (!stack.empty()) {
target.emplace_back(stack.top());
stack.pop();
}
return target;
}
};
解法2:利用链表指针进行链表翻转
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> target;
ListNode* next = head;
ListNode* pre = NULL;
while (NULL != next) {
next = head->next;
head->next = pre;
pre = head;
head = next;
}
while (NULL != pre) {
target.emplace_back(pre->val);
pre = pre->next;
}
return target;
}
};