题目描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数返回)。
示例 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
这个题目里面要求返回的是一个数组,所以完全没有必要改变链表的结构,只需要把链表里面的值拿出来,然后倒序输出就可以了。首先想到的是利用栈先进后出的性质,把链表的值压进栈里面,最后退出到一个要返回的数组里面就可以了;也可以通过list来做,将链表里面的值添加到list里面的值使用Collections.reverse函数倒序排列,最后输出到一个返回的数组了。
代码(Java):
public class doingmyself {
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(3);
head.next.next = new ListNode(2);
int[] res = reversePrint(head);
for(int i = 0;i<res.length;i++) {
System.out.print(res[i]+"\t");
}
}
public static int[] reversePrint(ListNode head) {
//使用栈
// Stack<Integer> stack = new Stack<Integer>();
// ListNode p = head;
// int len = 0;
// while(p!=null) { //把节点的值一个个推进栈里
// stack.push(p.val);
// len++;
// p = p.next;
// }
// int[] res = new int[len];
// for(int i = 0;i<len;i++) {
// res[i] = stack.pop();
// }
// return res;
//使用List
List<Integer> list = new ArrayList<Integer>();
ListNode p = head;
int size = 0;
while(p!=null) { //把节点的值一个个添加到列表里
list.add(p.val);
size++;
p = p.next;
}
Collections.reverse(list); //将列表里面的顺序倒过来
int[] res = new int[size];
for(int i = 0;i<size;i++) {
res[i] = list.get(i);
}
return res;
}
}