算法题:4、从尾到头打印链表

题目描述

从尾到头反过来打印出单向链表每个结点的值

Input:
1 -> 2 -> 3

Output:
3,2,1

解题思路

使用递归

要逆序打印链表,1->2->3,可以先逆序打印链表2->3,再打印1。而2->3可以看成一个新的链表,要逆序打印链表可以继续使用求解函数,也就是在求解函数中调用自己,这就是递归函数。

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    ArrayList<Integer> ret = new ArrayList<>();
    if (listNode != null) {
        ret.addAll(printListFromTailToHead(listNode.next));
        ret.add(listNode.value);
    }
    return ret;
}   

头插法

头结点和第一个节点都区别

  • 头结点是头插法中使用的一个额外节点,这个节点不存储值
  • 第一个结点就是链表的第一个真正存储值的节点
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    //头插法反转链表
    ListNode head = new ListNode(-1);
    while (listNode != null) {
        ListNode old = listNode.next;
        listNode.next = head.next;
        head.next = listNode;
        listNode = old;
    }

    ArrayList<Integer> res = new ArrayList();
    //找到反转链表的第一个节点
    head = head.next;
    while (head != null) {
        res.add(head.value);
        head = head.next;
    }
    return res;
}

使用栈

栈具有后进先出的特点,在遍历链表时,将值按顺序放入栈中,最后出栈的顺序即为逆序。

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    Stack<Integer> stack = new Stack<>();
    while (listNode != null) {
        stack.push(listNode.value);
        listNode = listNode.next;
    }

    ArrayList<Integer> res = new ArrayList<>();
    while (!stack.empty()) {
        res.add(stack.pop());
    }

    return res;
}
posted @ 2020-05-01 14:27  挣扎一下  阅读(112)  评论(0编辑  收藏  举报