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

    题目描述

    输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
     
    栈思路:
    /**
    *  struct ListNode {
    *        int val;
    *        struct ListNode *next;
    *        ListNode(int x) :
    *              val(x), next(NULL) {
    *        }
    *  };
    */
    class Solution {
    public:
        vector<int> printListFromTailToHead(ListNode* head) {
            vector <int> value;
            ListNode *p=NULL;
            p=head;
            stack <int> stk;
            while (p!=NULL){
                stk.push(p->val);
                p=p->next;
            }
            while (!stk.empty()){
                value.push_back(stk.top());
                stk.pop();
            }
            return value;
        }
    };
    #数组翻转 数组翻转可以用c++自带的函数,也可以自己实现
    /**
    *  struct ListNode {
    *        int val;
    *        struct ListNode *next;
    *        ListNode(int x) :
    *              val(x), next(NULL) {
    *        }
    *  };
    */
    class Solution {
    public:
        vector<int> printListFromTailToHead(ListNode* head) {
            vector <int> value;
            ListNode *p=NULL;
            p=head;
            while (p!=NULL){
                value.push_back(p->val);
                p=p->next;
            }
            int temp=0;
            int i=0,j=value.size()-1;
            while (i<j){
                temp=value[i];
                value[i]=value[j];
                value[j]=temp;
                i++;
                j--;
                
            }
            return value;
        }
    };
    #递归思路
    /**
    *  struct ListNode {
    *        int val;
    *        struct ListNode *next;
    *        ListNode(int x) :
    *              val(x), next(NULL) {
    *        }
    *  };
    */
    class Solution {
    public:
        vector< int> value;
        vector<int> printListFromTailToHead(ListNode* head) {
            ListNode *p=NULL;
            p=head;
            if (p!=NULL){
                if (p->next!=NULL){
                    printListFromTailToHead(p->next);
                }
                value.push_back(p->val);
            }
            return value;
        }
    };
     
     
     
     
     
     
  • 相关阅读:
    ( 三十一 )、 SpringBoot项目启动自动执行sql脚本
    转:OAuth 2.0 介绍
    采坑:python base64
    Redis学习——数据结构介绍(四)
    美化你的博客园,flash插件的使用
    Redis学习——详解Redis配置文件(三)
    Redis学习——Windows环境下Redis的安装(二)
    Redis学习——Linux环境下Redis的安装(一)
    NPM 安装速度慢,镜像修改
    日志配置(springboot、mybatis、Lombok)
  • 原文地址:https://www.cnblogs.com/hrnn/p/13338558.html
Copyright © 2011-2022 走看看