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;
}
相关推荐
juleskk3 分钟前
3.22 复试训练
算法
还不秃顶的计科生4 分钟前
力扣第84题:完全平方数
算法·leetcode·职场和发展
2301_776508728 分钟前
分布式系统监控工具
开发语言·c++·算法
暮冬-  Gentle°10 分钟前
C++与区块链智能合约
开发语言·c++·算法
愣头不青12 分钟前
78.子集
数据结构·算法
Oueii12 分钟前
C++中的代理模式实现
开发语言·c++·算法
3DVisionary16 分钟前
从微观损伤到宏观断裂:DIC非接触测量在复合材料可靠性验证中的前沿实践
人工智能·数码相机·算法·机器学习·3d·复合材料·dic技术
sheeta199817 分钟前
LeetCode 每日一题笔记 日期:2025.03.22 题目:1886.判断矩阵经轮转后是否一致
笔记·leetcode·矩阵
sonnet-102921 分钟前
拓扑排序的实现
java·c语言·开发语言·笔记·算法
米粒122 分钟前
力扣算法刷题 Day 20
算法·leetcode·职场和发展