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;
}
相关推荐
Doubbbbbbble云23 分钟前
多维空间索引结构R树与KD树性能对比研究4
算法
海上小飞龙24 分钟前
【KMP算法-中篇】next 数组的递推:往前填一位,靠的是往回退几步
算法
keyipatience28 分钟前
B树详解:从零构建平衡多路搜索树
数据结构·b树·算法·图搜索
FluxArt1 小时前
GPT Image 2.5 多图参考怎么用:Flux Art 生成与编辑教程
数据结构·gpt·算法
All for pursuit.1 小时前
【分治-2】215.数组中的第K个最大元素
数据结构·c++·算法·leetcode
CQU_JIAKE2 小时前
9.15【A】
算法·动态规划
成为深度学习高手2 小时前
DAG:沿时间与通道双相关建模的外生变量时序预测
网络·人工智能·深度学习·算法·机器学习·数据挖掘·时序数据库
阳明山水2 小时前
CEDAR双重解耦实现决策与干预分离
人工智能·深度学习·算法·机器学习·架构
w_zero_one2 小时前
链表(3)
java·数据结构·算法
Zootopia6262 小时前
美国载人飞船Crew-13明晚发射!
人工智能·算法·机器学习·数学建模·无人机·创业创新·信息与通信