输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
解法1:我首先想到的就是先遍历链表知道链表的长度,之后再遍历一次,然后把数值存入数组
Java代码:
public static int[] reversePrint(ListNode head) {
int i=0;
ListNode node=head;
while(node!=null)
{
node=node.next;
i++;
}
//System.out.print(i);
int[] nums=new int[i];
int j=i-1;
ListNode node1=head;
while(node1!=null)
{
nums[j]=node1.val;
node1=node1.next;
j--;
}
return nums;
}
解法2:利用栈的特性,先进先出
Java代码:
public static int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode node=head;
while(node!=null)
{
stack.push(node);
node=node.next;
}
int length=stack.size();
int[] nums=new int[length];
for(int i=0;i<length;i++)
{
nums[i]=stack.pop().val;
}
return nums;
}