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;
}
相关推荐
zlinear数据采集卡7 分钟前
D223的PWM电机控制:6路独立脉冲+加减速算法深度解析
arm开发·stm32·嵌入式硬件·算法·fpga开发·架构
杨石兴32 分钟前
31、玩具MoM:用2x2矩阵串起全套流程
人工智能·算法·矩阵·电磁学
江畔柳前堤40 分钟前
Function Calling 与 Tool Calling:从认知到工程的全景深度解析
开发语言·网络·人工智能·深度学习·算法·机器学习·php
Navigator_Z41 分钟前
LeetCode //C - 1192. Critical Connections in a Network
c语言·算法·leetcode
zander2581 小时前
LeetCode 739:每日温度——为什么单调栈要持续弹出
开发语言·python·算法
2601_955759881 小时前
如何降低 Claude API 批量生产返工率
大数据·人工智能·算法
布莱克6051 小时前
理解 C/C++ 中的 void* 指针
c语言·c++
rannn_1111 小时前
【力扣hot100】链表专题下|138、148、23、146
java·算法·leetcode·链表·开发
ly76891 小时前
分布式一致性算法详解:从 2PC、3PC 到 Paxos、Raft、ZAB
分布式·算法
(initial)2 小时前
C-05. Kernel Fusion 代价边界:少写回 vs 寄存器压力与 occupancy
c语言·开发语言·cuda