这篇文章将为大家详细讲解有关LeetCode如何从尾到头打印链表,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
0x01,问题简述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
0x02 ,示例
示例 1:
输入:head = [1,3,2]输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
0x03,题解思路
栈结构进行解决,已有的数据结构Stack
0x04,题解程序
import java.util.Stack;
public class ReversePrintTest { public static void main(String[] args) { ListNode l1 = new ListNode(1); ListNode l2 = new ListNode(3); ListNode l3 = new ListNode(2); l1.next = l2; l2.next = l3; int[] reversePrint = reversePrint(l1); for (int num : reversePrint ) { System.out.print(num + "\t"); }
}
public static int[] reversePrint(ListNode head) { if (head == null) { return new int[0]; } if (head.next == null) { return new int[]{head.val}; } Stack<Integer> stack = new Stack<>(); ListNode tempNode = head; while (tempNode != null) { stack.push(tempNode.val); tempNode = tempNode.next; } int[] result = new int[stack.size()];
int index = 0; while (!stack.isEmpty()) { result[index] = stack.pop(); index++; } return result; }}
0x05,题解程序图片版

关于“LeetCode如何从尾到头打印链表”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。