版权声明:个人博客:转载请注明出处 https://blog.csdn.net/weixin_43161811/article/details/82598828
题目描述
输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
1、用栈的思想实现链表的倒序输出
package com.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Stack;
public class LinkedListDemo {
public static ListNode2 head = new ListNode2(-1);// 头结点 保持不变
public static void main(String[] args) {
LinkedListDemo obj = new LinkedListDemo();
Random rand = new Random();
// 添加几个结点 十以内的随机数
for (int i = 0; i < 5; i++) {
ListNode2 listNode = new ListNode2(rand.nextInt(10));
obj.addNode(listNode);
}
// 打印所有结点的数据
System.out.print("链表原始数据顺序为:");
obj.printListNode();
List<Integer> list = obj.printListFromTailToHead(head);
// 打印所有结点的数据
System.out.print("链表从尾打到头:");
for (Integer integer : list) {
System.out.print(integer + " ");
}
}
// 从尾到头打印链表
public ArrayList<Integer> printListFromTailToHead(ListNode2 head) {
Stack<Integer> stack = new Stack<Integer>();
ListNode2 temp = head.next;
while (temp != null) {
stack.add(temp.data);
temp = temp.next;
}
ArrayList<Integer> list = new ArrayList<Integer>();
while (!stack.isEmpty()) {
list.add(stack.pop());
}
return list;
}
/**
* 增加操作
*
* @param listNode
*/
public void addNode(ListNode2 listNode) {
ListNode2 temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = listNode;
}
/**
*
* 打印结点
*
*/
public void printListNode() {
ListNode2 temp = head.next;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}
// 创建一个链表类
class ListNode2 {
int data;
ListNode2 next;
public ListNode2(int data) {
this.data = data;
}
}