首页 > 其他 > 详细

从尾到头打印链表

时间:2020-05-01 14:59:16      阅读:79      评论:0      收藏:0      [点我收藏+]

题目描述

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

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;
}

从尾到头打印链表

原文:https://www.cnblogs.com/fcb-it/p/12813429.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!