zoukankan      html  css  js  c++  java
  • [剑指Offer] 从尾到头打印链表

    问题描述

    输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

    分析

    链表只能顺序访问,但要求逆序地返回链表中的元素

    1. 遍历链表存到临时空间(栈或数组都行),再逆序输出到最终结果
    2. 反转链表,遍历链表到最终结果

    临时空间

    遍历链表,将数据插入栈,逆向遍历临时空间,将数据插入最终结果数组

    C++版

    // 使用vector作为临时空间
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> tmp;
        vector<int> result;
        if (head == NULL) return result;
        ListNode* tmpHead = head;
        while (tmpHead != NULL) {
            tmp.push_back(tmpHead->val);
            tmpHead = tmpHead->next;
        }
    
        int len = tmp.size();
        for(int i = len - 1; i >=0; --i) {
            result.push_back(tmp[i]);
        }
    
        return result;
    }
    
    // 使用stack作为临时空间
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> tmp;
        vector<int> result;
        if (head == NULL) return result;
        ListNode* tmpHead = head;
        while (tmpHead != NULL) {
            tmp.push(tmpHead->val);
            tmpHead = tmpHead->next;
        }
    
        while (!tmp.empty()) {
            result.push_back(tmp.top());
            tmp.pop();
        }
        return result;
    }
    

    Java版

    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> tmp = new ArrayList<Integer>();
        ArrayList<Integer> result = new ArrayList<Integer>();
        while (listNode != null) {
            tmp.add(listNode.val);
            listNode = listNode.next;
        }
        int len = tmp.size();
        for(int i = len-1; i >= 0; --i) {
            result.add(tmp.get(i));
        }
    
        return result;
    }
    

    反转单链表

    先reverse单链表,再遍历单链表,将数据插入最终结果

    vector<int> printListFromTailToHead(ListNode* head) {
        if (head == NULL || head->next == NULL) return {};
        ListNode* pre = NULL;
        ListNode* cur = head;
    
        while (cur != NULL) {
            ListNode* tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
    
        head = pre;
    
        vector<int> result;
        while (head != NULL) {
            result.push_back(head->val);
            head = head->next;
        }
    
        return result;
    }
    
  • 相关阅读:
    Java四种引用类型+ReferenceQueue+WeakHashMap
    浅谈怎样写好一篇(技术)博客?
    MySQL-5.7.14-WinX64安装配置详解
    网络编程梳理:Android网络基础知识复习
    Git时间:常用Git命令收集整理(持续更新)
    一些常见技术问题收集(二)持续更新
    开源库AndroidSwipeLayout分析(一),炫酷ItemView滑动呼出效果
    开源库AndroidSwipeLayout分析(二),SwipeLayout源码探究
    ES 基础操作
    pymongo
  • 原文地址:https://www.cnblogs.com/arcsinw/p/12945004.html
Copyright © 2011-2022 走看看