LeetCode //C - 206. Reverse Linked List

206. Reverse Linked List

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

Input head = [1,2,3,4,5]
Output [5,4,3,2,1]

Example 2:

Input head = [1,2]
Output [2,1]

Example 3:

Input head = []
Output []

Constraints:
  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

From: LeetCode

Link: 206. Reverse Linked List


Solution:

Ideas:
  • Initialize three pointers: prev (initially NULL), curr (pointing to the head of the list), and next (initially NULL).
  • Iterate through the list. In each iteration:
    • Store the next node in next.
    • Reverse the current node's next pointer to point to prev.
    • Move prev and curr one step forward.
  • After the loop, prev will point to the new head of the reversed list.
  • Update head to prev and return it.
Code:
c 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode *prev = NULL;
    struct ListNode *curr = head;
    struct ListNode *next = NULL;

    while (curr != NULL) {
        next = curr->next;  // Store next node
        curr->next = prev;  // Reverse current node's pointer
        prev = curr;        // Move pointers one position ahead
        curr = next;
    }

    head = prev;  // Update head to new first node
    return head;
}
相关推荐
m0_629494731 分钟前
LeetCode 热题 100-----27. 合并两个有序链表
数据结构·算法·leetcode·链表
玖釉-2 分钟前
Slang 和 HLSL 的区别与用法详解:现代图形渲染中的两种 Shader 编程语言
c++·算法·图形渲染
t-think3 分钟前
深入了解指针(3)
c语言·算法
GIOTTO情4 分钟前
Infoseek 危机公关自动化闭环系统,实现 PR 运维工程化
人工智能·算法·机器学习
hef2884 分钟前
利用C 图形界面展示MATLAB算法的高效混合编程实践
windows·算法·matlab
sali-tec5 分钟前
C# 基于OpenCv的视觉工作流-章76-轮廓-段距
图像处理·人工智能·opencv·算法·计算机视觉
水木流年追梦7 分钟前
大模型入门-RL基础
开发语言·python·算法·leetcode·正则表达式
城事漫游Molly14 分钟前
AI 快速生成标准化问卷分析报告:从 SUS 到 UMUX-LITE,如何把“分数”写成“结论”
人工智能·算法·机器学习·论文笔记·科研统计·问卷设计
人道领域19 分钟前
【LeetCode刷题日记】617.合并二叉树(空间换安全,还是原地省内存)
java·数据结构·算法·leetcode
linbaiwan66620 分钟前
PD和QC快充协议电压诱骗(取电)芯片:USB-C口支持PD,USB-A口支持QC
c语言·开发语言