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;
}
相关推荐
m0_565611133 分钟前
Java Stream流操作全解析
java·开发语言·算法
大千AI助手10 分钟前
决策树悲观错误剪枝(PEP)详解:原理、实现与应用
人工智能·算法·决策树·机器学习·剪枝·大千ai助手·悲观错误剪枝
乄夜14 分钟前
嵌入式面试高频!!!C语言(十四) STL(嵌入式八股文)
c语言·c++·stm32·单片机·mcu·面试·51单片机
九年义务漏网鲨鱼29 分钟前
【机器学习算法】面试中的ROC和AUC
算法·机器学习·面试
草莓熊Lotso30 分钟前
《算法闯关指南:优选算法--位运算》--38.消失的两个数字
服务器·c++·算法·1024程序员节
剪一朵云爱着6 小时前
力扣81. 搜索旋转排序数组 II
算法·leetcode·职场和发展
报错小能手9 小时前
刷题日常 5 二叉树最大深度
算法
Greedy Alg9 小时前
LeetCode 84. 柱状图中最大的矩形(困难)
算法
im_AMBER9 小时前
Leetcode 52
笔记·学习·算法·leetcode