剑指offer 从尾到头打印链表

题目描述

输入一个链表,从尾到头打印链表每个节点的值。

思路

总共有五种方法,如下:

  1. 将原链表的值存在一个栈中,然后再将栈输出到另一个vector数组里。
  2. 直接将原链表的值存在一个vector数组里,最后reverse翻转一下。
  3. 每插入一个,都放到最前面,复杂度是$n^{2}$,不是很高效。
  4. 通过递归到最后一个值,再一层一层输入到vector数组里。
  5. 直接将链表翻转。

代码

class Solution {
public:
  vector<int>printListFromTailToHead(ListNode*head) {
        int digit;
        stack<int> f;
        vector<int> res;
        ListNode *t = head;
        while(t != NULL)
        {
            f.push(t->val);
            t = t->next;
        }
        while(!f.empty())
        {
            digit = f.top();
            f.pop();
            res.push_back(digit);
        }
        return res;
    }
};
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        while(head != NULL)
        {
            res.push_back(head->val);
            head = head->next;
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int> res;
        if(head != NULL)
        {
            while(head != NULL)
            {    
               res.insert(res.begin(),head->val);
               head = head->next;
            }                      
        }
        return res;
    }
};
class Solution {
public:
    vector<int> res;
    vector<int> printListFromTailToHead(ListNode* head) {
        if(head!=NULL){
            printListFromTailToHead(head->next);
            res.push_back(head->val);
        }
        return res;
    }
};
class Solution {
public:
   vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        ListNode *pre = NULL;
        ListNode *p = NULL;
        while(head != NULL)
        {
            p = head->next; //p为head的下一个节点
            head->next = pre;//指向前一个节点
            pre = head;//向后移动
            head = p;//向后移动
        }
        while(pre != NULL)
        {
            res.push_back(pre->val);
            pre = pre->next;
        }
       return res;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 文章大纲:1.题目简介2.重点分析3.知识拓展 1.题目简介 输入一个链表的头结点,从尾到头反过来打印出每个节点的...
    柠檬乌冬面阅读 511评论 2 2
  • 说明: 本文中出现的所有算法题皆来自牛客网-剑指Offer在线编程题,在此只是作为转载和记录,用于本人学习使用,不...
    秋意思寒阅读 1,167评论 1 1
  • 剑指 offer 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成...
    faremax阅读 2,230评论 0 7
  • 1.把二元查找树转变成排序的双向链表 题目: 输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。 要求不...
    曲终人散Li阅读 3,357评论 0 19
  • 题目 不想打了,如题吧 1:逆置链表然后打印,这个做法的缺点是要改变输入的值,题目没有明确这个要求的话,做起来有风...
    clshinem阅读 137评论 0 1