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;
    }
    
  • 相关阅读:
    整数反转问题--正确率极低
    May LeetCoding Challenge9 之 求方差
    May LeetCoding Challenge8 之 交叉相乘
    EXCEL上传DEMO
    三层BOM
    OO alv 获取选择列
    PS 项目创建
    读取EXCEL到内表
    SAP XML 到 内表
    BOM 复制功能
  • 原文地址:https://www.cnblogs.com/arcsinw/p/12945004.html
Copyright © 2011-2022 走看看