想到了三个方法,分别是使用栈、倒序存入数组、递归。
方法1:使用栈:
思路:有了头节点,想要倒序输出链表,可以借助一个栈,将链表加入到栈当中去。再进行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) {
Stack<ListNode> s1 = new Stack<ListNode>();
int count=0;
while(head!=null){
s1.push(head);
head=head.next;
count++;
}
int[] arr= new int[count];
for(int i= 0;i<arr.length;i++){
arr[i]=s1.pop().val;
}
return arr;
}
}
方法2:倒序存入数组:
思路:因为拿到了头节点,想要倒序输出这个单向链表,可以先遍历一下链表,算出链表的长度。
根据链表长度创建数组,再循环将链表倒序给数组赋值。
迷惑点:第一次遍历计算长度时不能直接对head进行next操作,需要将其赋值给另一个节点head1,虽然他们指向的是同一个节点地址。但head1进行next操作时,只是head1指向下一个节点了。head依然指向头节点。
代码如下:
/**
* 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 count=0;
ListNode head1 = head;
while(head1!=null){
head1=head1.next;
count++;
}
int[] arr = new int[count];
while(head!=null){
arr[count-1]=head.val;
head=head.next;
count--;
}
return arr;
}
}
方法3:递归的终止条件为head.next==0。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
if(head==null){
return new int[0];
}
reversePrint1(head,1);
return arr;
}
int[] arr;
//递归
public void reversePrint1(ListNode node,int num){
if(node.next==null){
arr=new int[num];
arr[0]=node.val;
}else if(node.next!=null){
reversePrint1(node.next,num+1);
arr[arr.length-num]=node.val;
}
}
}