题目:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 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
解法一:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
int length=0;
ListNode node=head;
while(node!=null){
length++;
node=node.next;
}
int result[]=new int[length];
ListNode curr=head;
int i=0;
while(curr!=null){
result[i]=curr.val;
curr=curr.next;
i++;
}
int result1[]=new int[length];
for(int j=length-1;j>=0;j--){
result1[length-1-j]=result[j];
}
return result1;
}
}
解法二:
赋值方法更巧妙,参考了其他大佬的解法。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
int length=0;
ListNode node=head;
while(node!=null){
length++;
node=node.next;
}
int result[]=new int[length];
node=head;
for(int i=length-1;i>=0;i--){
result[i]=node.val;
node=node.next;
}
return result;
}
}
解法三:
使用栈,官方解法
/**
* 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> 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 newHead=reverse(head);
List<Integer> list=new ArrayList<Integer>();
while(newHead!=null){
list.add(newHead.val);
newHead=newHead.next;
}
Integer[] result=list.toArray(new Integer[list.size()]);
int[] re=new int[result.length];
for(int i=0;i<result.length;i++){
re[i]=result[i];
}
return re;
}
public ListNode reverse(ListNode head){
ListNode next=null;
ListNode pre=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}