从尾到头打印单链表(四种思路)

思路一:给一个标记的结点,表示所打印结点的下一个结点

在这里插入图片描述

  • 这个算法的时间复杂度为O(N^2),空间复杂度为O(1)
思路二:借助辅助空间

在这里插入图片描述

  • 这个算法的时间复杂度为O(N),空间复杂度为O(N)
思路三:递归
  • 如果想用递归来求解问题,首先要看这个问题能否利用递归来求解,也就是说看这个问题能否转换成它的子问题来求解,并且子问题要和原问题具有相同的解法,同时递归问题必须要有递归的出口
    在这里插入图片描述
例题:

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]

方法一:Reverse方法
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) 
    {
       //方法1:reverse反转法
        vector<int> res;
        while(head)
        {
            res.push_back(head->val);
            head = head->next;
        }
        //使用algorithm算法中的reverse反转res
        reverse(res.begin(),res.end());
        return res;
    }
};
方法二:借助栈
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) 
    {
       //方法2:入栈法
     	vector<int> res;
        stack<int> s;
        //入栈
        while(head)
        {
            s.push(head->val);
            head = head->next;
        }
        //出栈
        while(!s.empty())
        {
            res.push_back(s.top());
            s.pop();
        }
        return res;
    }
};
方法三:递归
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution 
{
public:
    vector<int> reversePrint(ListNode* head) 
    {
         //方法3:递归
        if(head == nullptr)
            return res;
        reversePrint(head->next);
        res.push_back(head->val);
        return res;
    }
};
方法四:改变链表结构
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution 
{
public:
    vector<int> reversePrint(ListNode* head) 
    {
        //方法4:改变链表结构
        ListNode *pre = nullptr;
        ListNode *next = head;
        ListNode *cur = head;
        while(cur)
        {
            next = cur->next;//保存当前结点的下一个节点
            cur->next = pre;//当前结点指向前一个节点,反向改变指针
            pre = cur;//更新前一个节点
            cur = next;//更新当前结点
        }
        while(pre)
        {
            //上一个while循环结束后,pre指向新的链表头
            res.push_back(pre->val);
            pre = pre->next;
        }
        return res;
    }
};
发布了80 篇原创文章 · 获赞 84 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43831728/article/details/105329232