leetcode算法题(反转链表)

思路1:

创建新的链表,遍历原链表,将原链表的节点进行头插到新链表中。

struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode* next = NULL;
    struct ListNode* new_head = NULL;
    if (head == NULL ||head->next == NULL) // 空链或只有一个结点,直回头
    {
        return head;
    }

    while (head != NULL) {
        next=head->next;
        head->next = new_head;
        new_head = head;
        head = next;
    }
    return new_head;
}

思路2:

创建三个节点,依次进行挪动。

struct ListNode* reverseList(struct ListNode* head) {
    if(head==NULL||head->next==NULL)
    {
        return head;
    }
    struct ListNode* n1,*n2,*n3;
    n1=NULL,n2=head,n3=n2->next;
    while(n2)
    {
        n2->next=n1;
        n1=n2;
        n2=n3;
        if(n3!=NULL)
        n3=n3->next;
    }
    return n1;
}

一张图搞懂上面的核心代码:

如果我的文章对你有帮助,期待你的三连!

相关推荐

  1. leetcode-

    2024-07-15 23:32:03       59 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-15 23:32:03       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-15 23:32:03       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-15 23:32:03       58 阅读
  4. Python语言-面向对象

    2024-07-15 23:32:03       69 阅读

热门阅读

  1. Linux

    2024-07-15 23:32:03       22 阅读
  2. RocketMQ入门指南:同步、异步、单向、延迟消息

    2024-07-15 23:32:03       22 阅读
  3. kubebuilder入门

    2024-07-15 23:32:03       19 阅读
  4. 嵌入式C语言常用技巧

    2024-07-15 23:32:03       19 阅读
  5. 独立站平台选择指南:WordPress 的优势与不足

    2024-07-15 23:32:03       20 阅读
  6. 国家自然科学基金 | 面上| 青基 | 联合 | 重点

    2024-07-15 23:32:03       21 阅读
  7. Spring常见的自定义和扩展的方法

    2024-07-15 23:32:03       20 阅读
  8. Flask 静态文件处理

    2024-07-15 23:32:03       18 阅读