剑指 Offer 06. 从尾到头打印链表

本文介绍了一种算法,该算法接收一个链表头节点,并从尾到头返回链表每个节点的值。通过两种方法实现:一是翻转链表再打印;二是直接按逆序填充数组。提供了详细的代码实现及时间、空间复杂度分析。

剑指 Offer 06. 从尾到头打印链表

剑指 Offer 06. 从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:
输入:head = [1,3,2]
输出:[2,3,1]

限制:
0 <= 链表长度 <= 10000


思路1:翻转链表

翻转链表,然后从头打印

翻转链表使用递归


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        //边界条件
        if(head == null) return new int[]{};
        if(head.next == null) return new int[]{head.val};

        //求出链表长度
        ListNode currentNode = head;
        int count = 0;
        while(currentNode != null){
            count++;
            currentNode = currentNode.next;
        }

        //又链表长度,建立数组
        int[] resultArray = new int[count];

        //翻转链表
        ListNode newHead = reverseList(head);

        //将翻转后的链表值,存储在数组里面
        for(int i = 0; i < count; i++){
            resultArray[i] = newHead.val;
            newHead = newHead.next;
        }

        return resultArray;
    }

    public ListNode reverseList(ListNode head){
        if(head == null) return null;
        if(head.next == null) return head;
        
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;

        return newHead;
    }
}

时间复杂度:O(3*n) = O(n)
空间复杂度:

链表翻转使用非递归:

public ListNode reverseList(ListNode head){
        if(head == null) return null;
        if(head.next == null) return head;
        
        ListNode newHead = new ListNode();
        while(head != null){
            ListNode tempNode = head.next;
            head.next = newHead.next;
            newHead.next = head;
            head = tempNode;
        }
        return newHead.next;
    }

时间复杂度:O(3*n) = O(n)
空间复杂度:O(n)

思路2:

求出链表长度,建立数组,将第一个节点值,存储在数组最后一个元素里面,依次类推

class Solution {
    public int[] reversePrint(ListNode head) {
        //边界条件
        if(head == null) return new int[]{};
        if(head.next == null) return new int[]{head.val};

        //求出链表长度
        ListNode currentNode = head;
        int count = 0;
        while(currentNode != null){
            count++;
            currentNode = currentNode.next;
        }

        //根据链表长度,建立数组
        int[] resultArray = new int[count];
        //将链表值,存储在数组里面
        for(int i = 0; i < count; i++){
            resultArray[count - i - 1] = head.val;
            head = head.next;
        }
        return resultArray;
    }
}

时间复杂度:O(2*n) = O(n)
空间复杂度:O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值