题目:
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
方法1:
利用递归的方式,终止条件为链表节点为空,循环返回节点数值存进集合中;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
ArrayList<Integer> objects = new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
digui(head);
int[] arr = new int[objects.size()];
for(int i=0;i<arr.length;i++){
arr[i]=objects.get(i);
}
return arr;
}
public void digui(ListNode head){
if(head==null)
return;
digui(head.next);
objects.add(head.val);
}
}
方法2:
采用比较骚气的方法,获取链表长度,将数组从后向前赋值
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
ListNode cur = head;
int count = 0;
while(cur!=null){
count++;
cur=cur.next;
}
int array[]=new int[count];
cur = head;
count--;
while(count>=0&&cur!=null){
array[count--] = cur.val;
cur = cur.next;
}
return array;
}
}
方法3:
利用栈的方法,先进后出的原则经行实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> stack = new LinkedList<Integer>();
while(head != null) {
stack.addLast(head.val);
head = head.next;
}
int[] res = new int[stack.size()];
for(int i = 0; i < res.length; i++)
res[i] = stack.removeLast();
return res;
}
}
知识总结:
1.ArrayList<Integer> objects = new ArrayList<Integer>();用在普通存储数据中
add()添加,get()取出;
2.LinkedList<Integer> stack = new LinkedList<Integer>();需要使用栈的时候定义
addLast()添加,removeLast()取出;