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

一、描述

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

  链表结点定义如下

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
原文地址:https://www.cnblogs.com/leesf456/p/5811879.html