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 小时前
jvm三色标记
java·jvm·算法
一车小面包2 小时前
逻辑回归 从0到1
算法·机器学习·逻辑回归
tt5555555555553 小时前
C/C++嵌入式笔试核心考点精解
c语言·开发语言·c++
科大饭桶3 小时前
C++入门自学Day14-- Stack和Queue的自实现(适配器)
c语言·开发语言·数据结构·c++·容器
tt5555555555553 小时前
字符串与算法题详解:最长回文子串、IP 地址转换、字符串排序、蛇形矩阵与字符串加密
c++·算法·矩阵
元亓亓亓4 小时前
LeetCode热题100--101. 对称二叉树--简单
算法·leetcode·职场和发展
不会学习?5 小时前
算法03 归并分治
算法
NuyoahC5 小时前
笔试——Day43
c++·算法·笔试
2301_821919925 小时前
决策树8.19
算法·决策树·机器学习
秋难降6 小时前
别再用暴力排序了!大小顶堆让「取极值」效率飙升至 O (log n)
python·算法·排序算法