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;
}
相关推荐
☆璇21 分钟前
【数据结构】栈和队列
c语言·数据结构
DoraBigHead2 小时前
小哆啦解题记——映射的背叛
算法
Heartoxx2 小时前
c语言-指针与一维数组
c语言·开发语言·算法
孤狼warrior2 小时前
灰色预测模型
人工智能·python·算法·数学建模
京东云开发者2 小时前
京东零售基于国产芯片的AI引擎技术
算法
chao_7893 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
十盒半价3 小时前
从递归到动态规划:手把手教你玩转算法三剑客
javascript·算法·trae
GEEK零零七4 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
凌肖战4 小时前
力扣网编程274题:H指数之普通解法(中等)
算法·leetcode
秋说4 小时前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法