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;
}
相关推荐
傻童:CPU18 分钟前
C语言需要掌握的基础知识点之前缀和
java·c语言·算法
degen_26 分钟前
第一次进入 PEICORE 流程
c语言·笔记
又见野草33 分钟前
软件设计师知识点总结:数据结构与算法(超级详细)
数据结构·算法·排序算法
我是大咖1 小时前
C语言-贪吃蛇项目开发工具篇---ncursee库安装
c语言·开发语言
GalaxyPokemon1 小时前
有一个服务器,用于提供HTTP服务,但是需要限制每个用户在任意的100秒内只能请求60次,怎么实现这个功能
算法
czy87874751 小时前
用C语言实现单例模式
c语言·单例模式
fl1768311 小时前
基于opencv+Mediapipe+CNN实现用手势识别控制对鼠标操控python源码+项目说明+设计文档
算法
K 旺仔小馒头1 小时前
优选算法:01 双指针巧解移动零问题
c++·算法·刷题
czy87874752 小时前
用C语言实现适配器模式
c语言·适配器模式
sali-tec2 小时前
C# 基于halcon的视觉工作流-章49-网面破损
开发语言·图像处理·算法·计算机视觉·c#