zoukankan      html  css  js  c++  java
  • 剑指offer(三):从尾到头打印链表

    题目描述

    输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
    C++实现:
    思想:入栈然后出栈即为逆序
    /**
    *  struct ListNode {
    *        int val;
    *        struct ListNode *next;
    *        ListNode(int x) :
    *              val(x), next(NULL) {
    *        }
    *  };
    */
    class Solution {
    public:
        vector<int> printListFromTailToHead(ListNode* head) {
            ListNode *p = head;
            vector<int> v;
            stack<int> s;
            while(p){
                s.push(p->val);
                p = p->next;
            }
            while(!s.empty()){
                v.push_back(s.top());
                s.pop();
            }
            return v;
        }
    };

    C++实现:

    利用C++ 的reverse函数直接实现逆置

    /**
    *  struct ListNode {
    *        int val;
    *        struct ListNode *next;
    *        ListNode(int x) :
    *              val(x), next(NULL) {
    *        }
    *  };
    */
    class Solution {
    public:
        vector<int> printListFromTailToHead(ListNode* head) {
            ListNode *p = head;
            vector<int> v;
            
            while(p){
                v.push_back(p->val);
                p = p->next;
            }
            reverse(v.begin(), v.end());
            return v;
        }
    };

     

    java实现:

    链表头插法实现原地逆置,要注意判空,否则会报空指针异常

    /**
    *    public class ListNode {
    *        int val;
    *        ListNode next = null;
    *
    *        ListNode(int val) {
    *            this.val = val;
    *        }
    *    }
    *
    */
    import java.util.ArrayList;
    public class Solution {
        public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
            ArrayList<Integer> list = new ArrayList<>();
            if(listNode==null)
               return list;
            
            ListNode L = listNode;
            ListNode nextL = L.next;
            ListNode newList = new ListNode(0);
    
            newList.next = L;
            L.next = null;
    
            while(nextL != null){
                L = nextL;
                nextL = nextL.next;
                L.next = newList.next;
                newList.next = L;
            }
            ListNode p = newList.next;
            while(p != null){
                list.add(p.val);
                p = p.next;
            }
            return list;
        }
    }

  • 相关阅读:
    网络日志流量分析-第一部分.doc
    Azkaban.Sqoop_网站流量日志分析2
    飞机加油问题
    9个点画10条直线,要求每条直线上至少3个点
    vector
    Selenium VS Webdriver
    B/S测试与C/S测试之区别
    几款代码比较工具
    单元测试-圈复杂度计算
    为什么并行测试很困难以及如何使用 ConTest 辅助测试
  • 原文地址:https://www.cnblogs.com/ttzz/p/13275781.html
Copyright © 2011-2022 走看看