剑指 Offer 06-----从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
import java.util.Stack;
/**
* @author LanceQ
* @version 1.0
* @time 2021/5/16 14:40
*/
public class reversePrintDemo {
public static void main(String[] args) {
ListNode a = new ListNode(1);
ListNode b = new ListNode(2);
ListNode c = new ListNode(3);
ListNode d = new ListNode(4);
ListNode e = new ListNode(5);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
System.out.println("以数组的形式打印链表的反转结果:");
// int[] x = reversePrint(a);
// int[] x = reversePrint1(a);
int[] x = reversePrint2(a);
System.out.print("[");
for (int i = 0; i < x.length; i++) {
if (i != x.length - 1)
System.out.print(x[i] + ",");
else {
System.out.print(x[i]);
}
}
System.out.print("]");
}
//不用栈,不用递归
public static int[] reversePrint(ListNode head) {
ListNode node = head;
int count = 0;
while (node != null) {
count++;
node = node.next;
}
int[] arr = new int[count];
node = head;
for (int i = count - 1; i >= 0; i--) {
arr[i] = node.val;
node = node.next;
}
return arr;
}
//递归
static int Count=0;
static int[] arr;
public static int[] reversePrint1(ListNode head){
reverse(head,0);
return arr;
}
private static void reverse(ListNode head, int index) {
if(head==null){
arr=new int[Count];
return;
}
Count++;
reverse(head.next,index+1);
arr[Count-index-1]=head.val;
}
//栈
private static int[] reversePrint2(ListNode head){
int count=0;
Stack<Integer> stack = new Stack<>();
while (head!=null){
stack.push(head.val);
head=head.next;
count++;
}
int[] ar=new int[count];
for (int i = 0; i < count; i++) {
if (!stack.isEmpty())
ar[i]=stack.pop();
}
return ar;
}
}
运行结果:
以数组的形式打印链表的反转结果:
[5,4,3,2,1]
- 第一种:先统计链表的长度,然后根据该长度对数组从后往前放入链表的数据,即完成了链表的数据反转。
- 第二种:通过递归的方式,探索的时候,记录链表的长度;在回溯的时候,通过记录的长度把聊表的数据放进数组中。
- 第三种:通过使用栈先进后出的特点,把链表的数据压进栈,并记录压进去的数量,然后通过统计的长度,逐个从栈中弹出数据,最后即完成了链表数据的反转。
参考:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof