思路:使用一个栈来保存元素,利用栈的先进后出的特性,逐个弹出栈中元素加入list集合,即可实现倒序输出。
package com.zf;
//倒序输出链表
import java.util.*;
//构造链表节点
public class JZ6 {
static class ListNode{
int val;
ListNode next=null;
public ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
//处理输入,同时构造成链表
Scanner sc=new Scanner(System.in);
String str=sc.next().toString();
String[] arr=str.split(",");
int[] ints=new int[arr.length];
for(int i=0;i<arr.length;i++){
ints[i]=Integer.parseInt(arr[i]);
}
ListNode head=new ListNode(ints[0]);
ListNode cur=head;
for(int i=1;i<ints.length;i++){
ListNode node=new ListNode(ints[i]);
cur.next=node;
cur=node;
}
List<Integer> list=solution(head);
System.out.println(list);
}
//封装方法
public static List<Integer> solution(ListNode head){
List<Integer> list=new ArrayList<>();
if(head==null) return list;
Stack<Integer> stack=new Stack<>();
ListNode cur=head;
while(cur!=null){
stack.push(cur.val);
cur=cur.next;
}
while(!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}
}