【面试】从尾到头打印链表

一、描述

  输入一个单链表的头结点,从尾到头反过来打印出每个结点的值。

  链表结点定义如下

class ListNode {
    int m_nKey;
    ListNode m_pNext;
}

二、解题思路

  此题有两种解题思路,一种是利用递归的方法打印,另外一种是在从头到尾遍历的过程中将结点的值保存至栈中,利用栈先进后出的特性,之后再依次打印栈中的结点元素即可。

三、代码

  根据如上的解题思路有如下的代码 

class ListNode {
    int m_nKey;
    ListNode m_pNext;

    public ListNode(int m_nKey, ListNode m_pNext) {
        this.m_nKey = m_nKey;
        this.m_pNext = m_pNext;
    }
}

public class PrintLinkList {
    public static void main(String[] args) {
        ListNode head = buildList();
        printList1(head);
        System.out.println();
        System.out.println("---------------------");
        printList2(head);
    }

    public static void printList1(ListNode head) {
        if (head.m_pNext != null) {
            printList1(head.m_pNext);
        }
        System.out.print(head.m_nKey + " ");
    }

    public static void printList2(ListNode head) {
        Stack<Integer> stack = new Stack<Integer>();
        while (head != null) {
            stack.push(head.m_nKey);
            head = head.m_pNext;
        }
        while (stack.size() != 0) {
            System.out.print(stack.pop() + " ");
        }
    }

    public static ListNode buildList() {
        ListNode ln6 = new ListNode(6, null);
        ListNode ln5 = new ListNode(5, ln6);
        ListNode ln4 = new ListNode(4, ln5);
        ListNode ln3 = new ListNode(3, ln4);
        ListNode ln2 = new ListNode(2, ln3);
        ListNode ln1 = new ListNode(1, ln2);

        return ln1;

    }
}

结果:

6 5 4 3 2 1 
---------------------
6 5 4 3 2 1

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值