题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
思路一
利用栈先进后出的特点,依次push()链表的值,然后再依次从栈中pop()取值存进返回数组中。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
//Step1:由于栈先进后出的特点,可以用来存储链表值
Stack<Integer> stack = new Stack<>();
int count = 0;
while(head != null){
ListNode temp = head;
stack.push(head.val);
count++;
head = head.next;
}
//Step2:定义辅助变量
int[] ret = new int[count];
count = 0;
while(!stack.isEmpty()){
ret[count++] = stack.pop();
}
//Step3:返回值
return ret;
}
}
思路二
可以将链表先进行反转,然后依次将值存入数组中。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
//Step1:定义辅助变量
ListNode ret = new ListNode(0);//声明了一个头结点
ret.next = null;
ListNode p = ret;
int count = 0;
//Step2:反转链表
while(head != null){
p = head;
head = head.next;//保存原来链表的指针
p.next = ret.next;
ret.next = p;
count++;
}
//Step3:依次将元素存入数组中
int[] res = new int[count];
for(int i = 0; i < count; i++){
ret = ret.next;//因为有头节点,所以先next,再赋值
res[i] = ret.val;
}
//Step4:返回结果
return res;
}
}
思路三
递归调用函数,再利用回溯法将值反序存入列表中,再将列表转换成数组。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
//全局变量
ArrayList<Integer> list = new ArrayList<>();
public int[] reversePrint(ListNode head) {
//Step1:递归调用
recur(head);//list已经存储了链表反序的值
//Step2:构建结果变量,并依次写入数组
int[] ret = new int[list.size()];
for(int i = 0; i < list.size(); i++){
ret[i] = list.get(i);
}
//Step3:返回结果变量
return ret;
}
public void recur(ListNode head){
//Step11:递归终止条件
if( head == null) return;
recur(head.next);
//Step12:添加该结点的值
list.add(head.val);
}
}