剑指Offer:面试题06.从尾到头打印链表
要点
- 场景是先进后出,栈或递归都可以
题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。示例 1:
输入:head = [1,3,2] 输出:[2,3,1]限制:
0 <= 链表长度 <= 10000代码
package com.yuyy.algorithm;
import java.util.Stack;
public class 从尾到头打印链表 {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
while(null!=head){
stack.push(head.val);
head=head.next;
}
int[] ints = new int[stack.size()];
int size=stack.size();
for (int i = 0; i < size; i++) {
ints[i]=stack.pop();
}
return ints;
}
private int[] arr;
private int k;
private int size;
public int[] reversePrint1(ListNode head) {
k=0;
size=0;
dg(head);
return arr;
}
public void dg(ListNode listNode){
size++;
if(null==listNode){
arr=new int[--size];
return;
}
dg(listNode.next);
arr[k++]=listNode.val;
}
public ListNode create(){
ListNode listNode = new ListNode(1);
ListNode listNode1 = new ListNode(3);
ListNode listNode2= new ListNode(2);
ListNode listNode3 = new ListNode(3);
ListNode listNode4 = new ListNode(4);
listNode.next=listNode1;
listNode1.next=listNode2;
// listNode2.next=listNode3;
// listNode3.next=listNode4;
return listNode;
}
public static void main(String[] args) {
从尾到头打印链表 clazz = new 从尾到头打印链表();
int[] arr=clazz.reversePrint1(clazz.create());
// int[] arr=clazz.reversePrint(new ListNode(1));
for (int i = 0; i < clazz.k; i++) {
System.out.println(arr[i]);
}
}
}
查看原文:http://yuyy.info/%e7%ae%97%e6%b3%95%e8%ae%ad%e7%bb%83/%e5%89%91%e6%8c%87offer%e9%9d%a2%e8%af%95%e9%a2%9806-%e4%bb%8e%e5%b0%be%e5%88%b0%e5%a4%b4%e6%89%93%e5%8d%b0%e9%93%be%e8%a1%a8/