题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路
方法一:先用栈保存依次保存链表的结点,之后用新的链表保存栈中的结点值即可。
方法二:利用一个新的结点不断保存前后两个节点的指向,从头到尾更改节点指向即可。
代码实现
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null)
return null;
Stack <ListNode> s = new Stack<ListNode>();
while(head!=null){
s.push(head);
head = head.next;
}
ListNode newhead = s.pop();
ListNode t = newhead;
while(!s.isEmpty()){
ListNode tmp = s.pop();
tmp.next = null;
t.next = tmp;
t = tmp;
}
return newhead;
}
}
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(listNode ==null){
return list;
}
ListNode prev = null;
ListNode now = listNode;
while(now != null){
//1.记录当前节点的下一个节点
ListNode next = now.next;
//2.修改当前节点指向为前一个
now.next = prev;
//3.修改完毕后,节点依次后移
prev = now;
now = next;
}
while(prev != null){
list.add(Integer.valueOf(prev.val));
prev = prev.next;
}
return list;
}
}