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;
}
相关推荐
智购科技智能售货柜2 小时前
2026自动售货机商品掉落声学计数方案:从麦克风到频谱识别的工程实践~YH
人工智能·算法
土司大王2 小时前
LeetCode hot100——实现 Trie (前缀树)
java·算法·leetcode
水龙吟啸2 小时前
华为研发岗AI方向9.9机考题复盘&分析
人工智能·python·算法·华为
小七在进步2 小时前
类和对象(一)
java·数据结构·算法
Y_Bk2 小时前
2026 ICPC EC网络预选赛第一场
算法
CarIise3 小时前
C语言字符串基础:从char数组到双指针反转算法
算法
佳児素花痴╮3 小时前
C++速通2
开发语言·c++·算法
麻瓜code3 小时前
【LeetCode】相交链表:双指针法,一次遍历找到交点
算法·leetcode·链表
zander2583 小时前
LeetCode 5. 最长回文子串
算法
hanlin034 小时前
刷题笔记:力扣第84题-柱状图中最大的矩形
笔记·算法·leetcode