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;
}
相关推荐
Ayanami_Reii11 分钟前
进阶数据结构应用-SPOJ 3267 D-query
数据结构·算法·线段树·主席树·持久化线段树
dangdang___go16 分钟前
文件操作c语言
c语言·开发语言
guygg881 小时前
基于全变差的压缩感知视频图像重构算法
算法·重构·音视频
尋有緣1 小时前
力扣1327-列出指定时间段内所有的下单产品
leetcode·oracle·数据库开发
VT LI1 小时前
SDF在实时图形渲染中的核心原理与架构创新
算法·sdf·有号距离场
想七想八不如114081 小时前
408操作系统 PV专题
开发语言·算法
天一生水water1 小时前
储层认知→技术落地→产量优化
人工智能·算法·机器学习
明洞日记1 小时前
【VTK手册019】 深入理解 vtkProperty:从几何表达到 PBR 物理渲染
c++·图像处理·算法·vtk·图形渲染
Genevieve_xiao1 小时前
【数据结构与算法】【xjtuse】面向考纲学习(下)
java·数据结构·学习·算法
修炼地1 小时前
代码随想录算法训练营第二十七天 | 56. 合并区间、738.单调递增的数字、968.监控二叉树
c++·算法