题解 | #从尾到头打印链表#

从尾到头打印链表

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;
    }
}

从尾到头打印。

我们可以两种解法,一种就是反转链表,反转后,再遍历,一种就是用栈直接记录,然后在遍历栈

全部评论

相关推荐

Twilight_m...:经典我朋友XXXX起手,这是那种经典的不知道目前行情搁那儿胡编乱造瞎指导的中年人,不用理这种**
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 13:47
机械打工仔:你自己匿名可以,这么好的公司就别给它匿名了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务