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;
}
相关推荐
民乐团扒谱机几秒前
【微实验】线性代数之——奇异值分解 SVD:穿透数据迷雾的“X光机”,附 MATLAB 全流程仿真
线性代数·算法·matlab
arin8763 分钟前
【图论】网络流
算法
_Narcissus_15 分钟前
B+树的概念和操作笔记(含完整代码实现)
c语言·数据结构·数据库·c++·笔记·b树·算法
aichitang202418 分钟前
快乐泛函每一天!内积空间
c++·python·数学·算法·机器学习·ai·泛函分析
octopus_c1 小时前
数据结构:二叉树
c语言·数据结构
茜茜数模1 小时前
2026年天府杯大学生数学建模A题全套资源
人工智能·算法·机器学习
PhotonixBay1 小时前
从粗糙度到三维形貌:激光共聚焦显微镜实现微米级表面分析
图像处理·人工智能·测试工具·算法
2401_862880821 小时前
数据结构 --- 算法
数据结构·算法
wuminyu2 小时前
JDK21中FFM api的upcall回调机制解析
java·linux·c语言·jvm·c++
个 人 练 习 生2 小时前
数据结构链表:带头双向循环链表
c语言·数据结构·经验分享·学习·其他·链表