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

从尾到头打印链表

http://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035

翻转链表

import java.util.ArrayList;
public class JZ3 {

    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {

        if (listNode == null){
            return new ArrayList<>();
        }

        if (listNode.next == null){
            return new ArrayList<>(listNode.val);
        }

        ListNode node = new ListNode(-1);
        ArrayList<Integer> res = new ArrayList<>();
        ListNode p = listNode;

        while (p != null){

            ListNode temp = p;
            p = p.next;
            temp.next = node.next;
            node.next = temp;
        }

        p = node.next;
        while (p != null){
            res.add(p.val);
            p = p.next;
        }
        return  res;
    }
}

class ListNode {
       int val;
       ListNode next = null;

       ListNode(int val) {
           this.val = val;
       }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务