LeetCode 206 反转列表

海超人and大洋游侠 2022-09-26 17:17:51

 递归法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *reverseList ( ListNode *head )
    {
        ListNode* answer = nullptr;
        while(head != nullptr){
            answer = new ListNode(head->val,answer);
            head = head->next;
        }
        return answer;
    }
};

三个指针法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *reverseList ( ListNode *head )
    {
        ListNode* first = head;
        ListNode* second = nullptr;
        while(first != nullptr) {
            ListNode* next = first->next;
            first->next = second;
            second = first;
            first = next;
        }
        return second;
    }
};

 

...全文
95 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

95

社区成员

发帖
与我相关
我的任务
社区描述
算法交流
社区管理员
  • 算法时空
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧