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;
}
相关推荐
折哥的程序人生 · 物流技术专研7 小时前
Java面试85题图解版 · 特别篇:2026后端高频面试题复盘(算法底层逻辑+高并发架构设计全解析,附Java实战代码)
java·网络·数据库·算法·面试
玖玥拾8 小时前
C/C++ 基础笔记(十四)多态与模板编程
c语言·c++·多态·模板
想吃火锅10058 小时前
【leetcode】14.最长公共前缀js
算法·leetcode·职场和发展
云絮.9 小时前
数据库操作
数据库·mysql·算法·oracle
小林ixn10 小时前
LeetCode 206. 反转链表(迭代 + 递归详解)
算法·leetcode·链表
凡人叶枫10 小时前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法
菜鸟‍11 小时前
LeetCode 1 27 和 704 || 两数之和 移除元素 二分查找
算法·leetcode·职场和发展
caimouse12 小时前
Reactos 第1章 概述
c语言·开发语言·架构
退休倒计时13 小时前
【每日一题】LeetCode 142. 环形链表 II TypeScript
算法·leetcode·链表·typescript
啊森要自信13 小时前
【GUI自动化测试】控件、鼠标键盘操作与多场景自动化
c语言·开发语言·python·adb·ipython