剑指offer面试题6:从尾到头打印链表

题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值。

**注意:**面试中,如果打算修改输入的数据,最好先问面试官是否允许修改,如上题是否可以反转链表,改变原来链表的结构。

思路1:从尾到头打印,即“后进先出”,可以采用栈实现。每经过一个节点,就入栈,遍历完整个链表的时候,依次输出栈顶的值。

思路2:用递归实现,递归本质是一个栈结构。即每访问一个节点的时候,先递归输出该节点的后继节点,再输出该节点本身。

import java.util.Stack;

/**
 * @author: zjay
 * @version: 1.0
 * @date: 2021/8/12
 *
 * 题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值。
 *
 * 思路1:从尾到头打印,即“后进先出”,可以采用栈实现。每经过一个节点,就入栈,
 * 遍历完整个链表的时候,依次输出栈顶的值。
 *
 * 思路2:用递归实现,递归本质是一个栈结构。即每访问一个节点的时候,先递归输出该节点的后继节点,
 * 再输出该节点本身。
 */
public class Test6_PrintListReverse1 {
    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;//建立链表

        printListReverse2(node1);//方法测试
    }

    //利用堆结构逆序输出
    public static void printListReverse1(Node head){
        Stack<Node> stack = new Stack<Node>();
        Node temp = head;
        //若链表只有一个节点或者为空,则返回
        if(head == null || head.next == null) {
            return;
        }
        while (temp != null) { //遍历,入栈
            stack.push(temp);
            temp = temp.next;
        }
        while (!stack.isEmpty()) {//出栈,输出
            System.out.println(stack.pop().value);
        }

    }

    //利用递归逆序输出链表
    public static void printListReverse2(Node head) {
        if (head != null) { // while(head != null) 一般递归用if判断,非递归用while.递归必须由递归结束条件
            if(head.next != null) {
                printListReverse2(head.next);//递归
            }
        }
        System.out.println(head.value);
    }
}

//节点类
class Node{
    public int value;
    public Node next;

    public Node(int value) {
        this.value = value;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值