leetcode:面试题06. 从尾到头打印链表

题目来源

面试题06. 从尾到头打印链表

题目描述

在这里插入图片描述

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
    vector<int> reverseBookList(ListNode* head) {

    }
};

题目解析

使用stack

栈的特点是后进先出,即最后压入栈的元素最先弹出。考虑到栈的这一特点,使用栈将链表元素顺序倒置。从链表的头节点开始,依次将每个节点压入栈内,然后依次弹出栈内的元素并存储到数组中。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        while (head != null) {
            stack.push(head.val);
            head = head.next;
        }
        int size = stack.size();
        int[] array = new int[size];
        for (int i = 0; i < size; i++) {
            array[i] = stack.pop();
        }
        return array;
    }
}

在这里插入图片描述

链表反转

反转链表的同时记下链表长度,然后填充数组

class Solution {
    public int[] reversePrint(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        int size = 0;
        while (cur != null){
            ListNode t = cur.next;
            cur.next = pre;
            pre = cur;
            cur = t;
            size++;
        }


        int[] arr = new int[size];
        size = 0;
        while (pre != null){
            arr[size++] = pre.val;
            pre = pre.next;
        }


        return arr;
    }
}

在这里插入图片描述

反向填充数组

先求出链表长度,构建数组,然后反向填充数组

class Solution {
    public int[] reversePrint(ListNode head) {
           int size = 0;
        ListNode temp = head;
        while (head != null){
            head = head.next;
            size++;
        }


        int[] arr = new int[size];
        for (int i = size - 1; i > -1 ; i--){
            arr[i] = temp.val;
            temp = temp.next;
        }

        return arr;
    }
}

在这里插入图片描述

vector<int> reversePrint(ListNode* head) {
   vector<int> ans;
   ListNode *iter = head;
   while (iter){
       ans.insert(ans.begin(), iter->val);
       iter = iter->next;
   }
    return ans;
}

递归

一个后序遍历

class Solution {
    vector<int> ans;
    void helper(ListNode* head){
        if(head == nullptr){
            return;
        }

        helper(head->next);
        ans.emplace_back(head->val);
    }
public:
    vector<int> reversePrint(ListNode* head) {
        helper(head);
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值