输入一个链表,从尾到头打印链表每个节点的值
/**
* 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> res=new ArrayList<>();
if(listNode==null)
return res;
ListNode head=new ListNode(0);
ListNode pre=null,cur=listNode;
while(cur!=null){
ListNode tmp=cur.next;
if(cur.next==null){
head.next=cur;
}
cur.next=pre;
pre=cur;
cur=tmp;
}
cur=head.next;
while(cur!=null){
res.add(cur.val);
cur=cur.next;
}
return res;
}
}
//运行时间:36ms占用内存:9156k
思考:
1、问题中是否可以修改原本的链表
2、可以修改的话,如上述代码中,先反转链表,再遍历打印链表
3、不可以修改的话,可以考虑采用栈来实现,如下代码所示:
import java.util.*;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<ListNode> st=new Stack<>();
ArrayList<Integer> res=new ArrayList<>();
if(listNode==null){
return res;
}
ListNode cur=listNode;
while(cur!=null){
st.push(cur);
cur=cur.next;
}
while(!st.isEmpty()){
res.add(st.pop().val);
}
return res;
}
}
运行时间:35ms占用内存:9352k
二刷剑指offer,争取每个题目都能完全掌握一种基本方法,再会一种改进的优化解法