题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
package com.hwx.swordToOffer._03_printListFromTailToHead;
import java.util.ArrayList;
import java.util.Stack;
/*
* 题目描述:
* 输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
*/
public class Solution {
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
node1.next=node2;
node2.next=node3;
node3.next=node4;
System.out.println(printListFromTailToHead(node1));
}
/*
* 我的方法:使用栈"先进后出"的结构
*/
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode==null){
//注意:这里不能直接返回null,否则测试案例不通过,因为测试案例是将ArrayList进行打印,
//输入null,返回[]不是null;也可以不写这句判断语句,为null时直接返回空的ArrayList
return new ArrayList<Integer>();
}
Stack<Integer> stack=new Stack<>();
ListNode cur=listNode;
while(cur!=null) {
stack.push(cur.val);
cur=cur.next;
}
ArrayList<Integer> list = new ArrayList<>();
while(stack.size()>0) {
list.add(stack.pop());
}
return list;
}
/*
* 不使用栈结构,直接在原链表上进行操作,不难但也有一点技术含量,要会掌握
*/
public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
ArrayList<Integer> list=new ArrayList<Integer>();
ListNode pre=null;//即新链表的头节点
ListNode next=null;//当前节点的下一个节点
while(listNode!=null){
next=listNode.next;//重要!!!!保存当前节点的下一个节点
listNode.next=pre;//将当前节点连接到新链表的头部,即当前节点为的下一节点为新链表的头节点
pre=listNode;//在将新链表的头节点前移一个,来到最新的头节点
listNode=next;//当前节点往后移动,为原始链表的下一个节点
//while循环结束后listNode指向null,pre指向新链表的头节点
}
while(pre!=null){
list.add(pre.val);
pre=pre.next;
}
return list;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}