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;
}
相关推荐
秦苒&几秒前
【C语言指针五】转移表、回调函数、qsort、qsort函数的模拟实现
c语言·开发语言·c#
Tisfy3 分钟前
LeetCode 960.删列造序 III:动态规划(最长递增子序列)
算法·leetcode·动态规划·字符串·题解·逆向思维
多米Domi0115 分钟前
0x3f第十天复习(考研日2)(9.18-12.30,14.00-15.00)
python·算法·leetcode
旧梦吟8 分钟前
脚本网页 C与汇编详解
c语言·css3·html5
listhi5209 分钟前
支持向量机多分类解决方案
算法·支持向量机·分类
十三画者10 分钟前
【文献分享】vConTACT3机器学习能够实现可扩展且系统的病毒分类体系的构建
人工智能·算法·机器学习·数据挖掘·数据分析
TrueFurina(互关互赞)23 分钟前
7-4 区间水仙花数 Python程序设计-MJU实验四(编程入门•多代码实现•测试均通过)
数据结构·算法·飞书·创业创新·学习方法·远程工作·改行学it
Amnesia0_024 分钟前
Map和Set
算法
受伤的僵尸25 分钟前
算法类复习(1)-非自注意力机制(图像处理中的注意力)
人工智能·算法
晨非辰27 分钟前
基于Win32 API控制台的贪吃蛇游戏:从设计到C语言实现详解
c语言·c++·人工智能·后端·python·深度学习·游戏