题解 | #从尾到头打印链表#
从尾到头打印链表
https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
/** * public class ListNode { * int val; * ListNode next = null; * * ListNode(int val) { * this.val = val; * } * } * */ import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode head) { ListNode dummpHead = new ListNode(-1); dummpHead.next = head; ListNode cur = head; ArrayList<Integer> arrayList = new ArrayList<Integer>(); Deque<Integer> deque = new LinkedList<Integer>(); // while(cur!=null){ // ListNode next = cur.next; // cur.next = next.next; // next.next = cur; // dummpHead.next = next; // } while (dummpHead.next != null) { deque.push(dummpHead.next.val); dummpHead.next = dummpHead.next.next; } while(!deque.isEmpty()){ arrayList.add(deque.pop()) ; } return arrayList; } }
从尾到头打印。
我们可以两种解法,一种就是反转链表,反转后,再遍历,一种就是用栈直接记录,然后在遍历栈