前言
leetcode上,剑指offer,从尾到头打印链表:
题目地址
基本知识
什么是链表:
链表是一种数据结构,里面存放了一系列数据,类似于数组。不同之处在于,数组中的数据在内存中的存储空间是连续的,因此可以直接通过元素的索引取出元素。但链表中的数据在内存中的存储空间不是连续的,链表的每一个数据节点包含数据、指向下一个节点的指针两部分,因此链表获取某个特定节点,只能从头一个一个往下找。
链表的优点在于,不需要连续的存储单元,修改节点的复杂度较低,数据在修改节点时,需要把其余所有的元素移动位置,复杂度较高。
链表的缺点在于,查询元素的时间复杂度较高,只能从头到尾一个一个查,时间复杂度为O(n)
解题思路
1.递归
先走到链表的末端,然后回溯,依次将节点添加至数组中,返回该数组(注意,这里需要使用可变数组,因为不把链表遍历完,也不知道这个数组有多大,同时,由于题目中要求的返回值是int,而不是ArrayList,所以还需要调整一下)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
ArrayList<Integer> tmp = new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
recur(head);
int[] res = new int[tmp.size()];
for(int i = 0;i < res.length; i++){
res[i] = tmp.get(i);
}
return res;
}
public void recur(ListNode head){
if(head == null){
return;
}
recur(head.next);
tmp.add(head.val);
}
}
2.辅助栈
借助栈,先进后出的特性,把链表里面的元素一个一个压到栈里面,然后从栈里面一个一个弹出来到数组里面返回就可以
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack1 = new Stack<ListNode>();
ListNode tmp = head;
while(tmp != null){
stack1.push(tmp);
tmp = tmp.next;
}
int size = stack1.size();
int[] res = new int[size];
for(int i=0;i<size;i++){
res[i] = stack1.pop().val;
}
return res;
}
}
注意,stack1.size()这里最好写死,因为下面你的stack就pop出来元素了,不写死的话,for循环里面的i的限制条件会变化,导致输出不对