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;
}
相关推荐
Giser探索家几秒前
建筑物孪生模型:重构空间数字化格局,赋能智慧城市
大数据·人工智能·算法·重构·分类·云计算·智慧城市
Tiny番茄22 分钟前
leetcode 3. 无重复字符的最长子串
数据结构·python·算法·leetcode
什么半岛铁盒2 小时前
C++11 多线程与并发编程
c语言·开发语言·c++
WHS-_-20224 小时前
A Density Clustering-Based CFAR Algorithm for Ship Detection in SAR Images
算法·5g
Kiri霧6 小时前
Linux下的Rust 与 C 的互操作性解析
c语言·开发语言·rust
Miraitowa_cheems6 小时前
LeetCode算法日记 - Day 68: 猜数字大小II、矩阵中的最长递增路径
数据结构·算法·leetcode·职场和发展·贪心算法·矩阵·深度优先
迎風吹頭髮7 小时前
UNIX下C语言编程与实践62-UNIX UDP 编程:socket、bind、sendto、recvfrom 函数的使用
c语言·单片机·unix
灵感__idea8 小时前
Hello 算法:让前端人真正理解算法
前端·javascript·算法
学习2年半9 小时前
小米笔试题:一元一次方程求解
算法
MATLAB代码顾问9 小时前
MATLAB绘制多种混沌系统
人工智能·算法·matlab