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;
        }
    }

  • 相关阅读:
    golang sql连接池的实现解析
    golang使用rabbitmq正确姿势
    golang使用rabbitmq多个消费者
    golang网关之手动实现反向代理
    golang exec.Command执行脚本 杀死子进程
    exec: "gcc": executable file not found in %PATH%
    golang操作mongodb
    grpc之 普通流 、服务端流、 客户端流 、双向流模式
    grpc-POST提交主订单数据(gateway实现http api)
    grpc之protobuf常用语法速学
  • 原文地址:https://www.cnblogs.com/ttzz/p/13275781.html
Copyright © 2011-2022 走看看