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;
    }
    
  • 相关阅读:
    昆石VOS3000_2.1.4.0完整安装包及安装脚本
    KVPhone,VOS官方的SIP软电话电脑客户端
    昆石VOS2009 VOS3000无漏洞去后门电脑管理客户端大全
    2017年最新(4月20日)手机号码归属地数据库分享
    2017年最新VOS2009/VOS3000最新手机号段导入文件(手机归属地数据)
    Android:onNewIntent()
    三星S4使用体验(Markdown版)
    apple公司的潮起潮落——浪潮之巅
    microsoft的罗马帝国——浪潮之巅
    我的iOS开发之路
  • 原文地址:https://www.cnblogs.com/arcsinw/p/12945004.html
Copyright © 2011-2022 走看看