import java.util.ArrayList;
import java.util.Stack;
/**
* 面试题6:从尾到头打印链表
* 题目:输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
*
* @author dengjie
* @create 2021-03-10 12:44
*/
public class Solution6 {
static ArrayList<Integer> arrayList = new ArrayList<>();//方法三递归时使用
public static void main(String[] args) {
ListNode node = new ListNode(67);
ListNode node1 = new ListNode(0);
ListNode node2 = new ListNode(24);
ListNode node3 = new ListNode(58);
node.next = node1;
node1.next = node2;
node2.next = node3;
System.out.println(node);
ArrayList<Integer> res = printListFromTailToHeadByRecursive(node);
System.out.println(res);
}
/**
* 方法1:list.add(index,ele),在0位置处添加元素实现反转输出
* @param listNode
* @return
*/
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode){
ArrayList<Integer> arr = new ArrayList<>();
while (listNode != null){
arr.add(0,listNode.val);
listNode = listNode.next;
}
return arr;
}
/**
* 方法二:栈
*/
public static ArrayList<Integer> printListFromTailToHeadByStack(ListNode listNode){
Stack<Integer> stack = new Stack<>();
ArrayList<Integer> arrayList = new ArrayList<>();
while (listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
while (!stack.empty()){
arrayList.add(stack.pop());
}
return arrayList;
}
/**
* 方法三:递归
*/
public static ArrayList<Integer> printListFromTailToHeadByRecursive(ListNode listNode){
//注意是if不是while
if (listNode != null){
printListFromTailToHeadByRecursive(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
}
class ListNode{
int val;
ListNode next = null;
public ListNode(int val){
this.val = val;
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
", next=" + next +
'}';
}
}
【剑指Offer】面试题6:从尾到头打印链表
最新推荐文章于 2024-02-28 18:26:20 发布