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

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

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

class Node {
	int key;
	Node next;
}

解法一:

遍历链表,并使用栈来保存节点信息,遍历结束后,从栈中输出结果。

package Question06;

import java.util.Stack;

public class T01 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 2, 5, 3, 5, 6, 7, 5, 3};
        LinkedList linkedList = new LinkedList(arr);
        linkedList.add(9);
        linkedList.printListFromLast();
    }
}

class LinkedList {
    Node head = new Node(-1);

    public LinkedList(int[] arr) {
        Node cur = head;
        for(int i = 0; i < arr.length; i++) {
            Node temp = new Node(arr[i]);
            cur.next = temp;
            cur = cur.next;
        }
    }

    public void add(int key) {
        Node cur = head;
        while(cur.next != null) cur = cur.next;
        Node temp = new Node(key);
        temp.next = cur.next;
        cur.next = temp;
    }

    public void printListFromLast() {
        Stack<Integer> stack = new Stack<>();
        Node cur = head.next;
        while(cur != null) {
            stack.push(cur.key);
            cur = cur.next;
        }
        while(!stack.empty()) {
            System.out.println(stack.pop());
        }
    }
}

class Node {
    public int key;
    public Node next;

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

解法二:使用递归来操作

public void printListFromLast2(Node temp) {
    if(temp == null) return ;
    printListFromLast2(temp.next);
    if(temp != head) System.out.println(temp.key);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值