[AcWing 35] 反转链表

image

迭代版本

点击查看代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head || !head->next)   return head;
        auto a = head, b = a->next;
        while (b) {
            auto c = b->next;
            b->next = a;
            a = b, b = c;
        }
        head->next = NULL;
        return a;
    }
};

  1. 当是空链表或只有一个结点时,直接返回头结点 head;
  2. 当 b 不为空时,a 指向当前结点 p,b 指向 p->next,c 指向 p->next->next,每次将 b->next = a,并移动指针 a = b, b = c;
  3. head 此时指向的是新链表的尾结点,head->next = NULL;
  4. 新链表的头结点是 a;

递归版本

点击查看代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head || !head->next)   return head;
        auto tail = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return tail;
    }
};

  1. 当是空链表或只有一个结点时,直接返回头结点 head;
  2. 递归调用 reverseList(head->next),最后一次递归,反转链表尾结点为 head->next,head->next->next = NULL,此时执行 head->next->next = head 对 head 结点进行反转,head 变为新的反转链表的尾结点,head->next = NULL;
  3. 返回的 tail 是反转链表的头结点;
posted @   wKingYu  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
欢迎阅读『[AcWing 35] 反转链表』
点击右上角即可分享
微信分享提示