【Leetcode】3从尾到头打印链表

题目:输入一个链表,按链表值从尾到头的顺序返回

思路:链表是一个节点指向下一个节点的单向链式结构,无法逆向访问。所以无论如何,先把链表里的东西放到一个容器内,然后要么放的时候倒序放,要么返回容器之前将容器翻转,再返回容器。

方法1:递归。递归就是函数本身再调用自身。

class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int> value;//定义一个vector存放结果
        if(head != NULL)
        {
            value.insert(value.begin(),head->val);//将链表的头插到容器的头
            if(head->next != NULL)
            {
                vector<int> tempVec = printListFromTailToHead(head->next);//使用递归的地方。将剩下的部分也插到头,剩下的部分内部也这样循环处理
                if(tempVec.size()>0)
                value.insert(value.begin(),tempVec.begin(),tempVec.end());  
            }         
             
        }
        return value;
    }
};

方法2:头插入

最简单,但是效率低,就依次读取链表的内容,并把内容放到容器里的头部。

class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int> value;
        if(head != NULL)
        {
            value.insert(value.begin(),head->val);//依次读取,将内容插入到头部
            while(head->next != NULL)
            {
                value.insert(value.begin(),head->next->val);
                head = head->next;
            }         
             
        }
        return value;
    }
};

方法3:库函数:reverse

也简单,就依次读取链表内容,push_back到容器里,然后使用reverse函数

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> result;
        if(head!=NULL)
        {
            result.push_back(head->val);
            while(head->next!=NULL)
            {
                result.push_back(head->next->val);//直接把链表内容放到vector里
                head=head->next;
            }
        }
        reverse(result.begin(),result.end());//最后返回之前将vector翻转
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/ethan_guo/article/details/81128717