从尾到头打印链表(Stack栈)
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Java知识点:
栈也是一种动态对象数组,采用的是一种先进后出的数据结构形式,即在栈中最早保存的数据最后才会取出,而最后保存的数据可以最先取出 。
No. | 方法 | 类型 | 描述 |
---|---|---|---|
1 | public E push(E item) | 普通 | 数据入栈 |
2 | public E pop() | 普通 | 数据出栈,如果栈中没有数据,则调用此方法会抛 出空栈异常(EmptyStackException) |
用 Stack 类的 push()方法向栈中保存数据,而取得数据时只需要利用 pop()方法即可实现出栈操作,如果栈中没有任何数据,进行出栈操作时则将抛出“EmptyStackException”异常,通过size()可以获取栈的大小。
方法一:使用Stack类(栈)
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode temp = head;
while (temp != null) {
stack.push(temp);
temp = temp.next;
}
int size = stack.size();
int[] print = new int[size];
for (int i = 0; i < size; i++) {
print[i] = stack.pop().val;
}
return print;
}
}
方法二:还可以通过迭代的方法反转链表
class Solution {
public int[] reversePrint(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next; //curr != null就可以一直迭代,每次循环由旧值得到新值,新值作为继续的条件
}
ListNode currentNode = prev;//反转后为尾结点,指向前一个节点
List list = new ArrayList();
while (currentNode != null) { // 当前节点存在数据
list.add(currentNode.val);
currentNode = currentNode.next ; // 将下一个节点设置为当前节点
}
int[] a = new int[list.size()];
for (int i =0;i<a.length;i++){
a[i] = (int) list.get(i);
}
return a;
}
}