剑指Offer06 从尾到头打印链表

剑指Offer06 从尾到头打印链表

题目

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

限制:

0 <= 链表长度 <= 10000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

​ 我觉得**这个题目有问题**!

​ 头结点是单链表第一个节点之前的节点,没有前驱节点。leetcode给的答案把头结点当成这了首节点,我自己写传入头结点反而错了。所以这里请注意区分链表的**头结点首节点!**

代码

传入头结点, 附完整节点、链表实现和测试代码。

/**
 * @version V1.0
 * @ClassName:Offer06
 * @Description: 从尾到头打印链表
 * @author:Daniel
 * @date:2021/1/20 下午4:10
 */
public class Offer06 {
    
    

    public static void main(String[] args) {
    
    

        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(2);

        LinkedList list = new LinkedList();
        list.add(node1);
        list.add(node2);
        list.add(node3);

        int[] ints = reversePrint(list.getHead());
        System.out.println(Arrays.toString(ints));


    }

    // 方法一:使用堆栈
    public static int[] reversePrint(ListNode head) {
    
    
        // 判断链表是否为空
        if (head.next == null) {
    
    
            return null;
        }
        Stack<ListNode> stack = new Stack<>();
        // 定义一个辅助变量指向当前节点
        ListNode curNode = head.next;
        // 先将所有的节点压入栈
        while (true) {
    
    
            if (curNode == null) {
    
    
                break;
            }
            stack.push(curNode);
            curNode = curNode.next;
        }
        int[] results = new int[stack.size()];
        int index = 0;
        // 然后将所有的节点出栈,实现从尾到头打印
        while (stack.size() > 0) {
    
    
            results[index++] = stack.pop().val;
        }
        return results;
    }
}

class LinkedList {
    
    
    private ListNode head = new ListNode(0);

    // 返回头结点
    public ListNode getHead() {
    
    
        return head;
    }

    // 增加节点
    public void add(ListNode node) {
    
    
        // 遍历到链表的最后,然后插入节点
        ListNode curNode = head;
        while (true) {
    
    
            if (curNode.next == null) {
    
    
                break;
            }
            curNode =  curNode.next;
        }
        curNode.next = node;
    }
}

class ListNode {
    
    
    int val;
    ListNode next;
    ListNode(int x) {
    
     val = x; }
}

猜你喜欢

转载自blog.csdn.net/DDDDeng_/article/details/112898219