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:
/**
 * 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;
}

相关推荐

  1. LeeetCode 206

    2024-01-16 14:02:01       52 阅读
  2. [链表专题]力扣206, 203, 19

    2024-01-16 14:02:01       35 阅读
  3. leetcode-206-翻转链表

    2024-01-16 14:02:01       56 阅读
  4. LeetCode206链表相交

    2024-01-16 14:02:01       54 阅读
  5. 206. 反转链表

    2024-01-16 14:02:01       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-16 14:02:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-16 14:02:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-16 14:02:01       87 阅读
  4. Python语言-面向对象

    2024-01-16 14:02:01       96 阅读

热门阅读

  1. 关于js学习-初体验

    2024-01-16 14:02:01       63 阅读
  2. js some方法的使用

    2024-01-16 14:02:01       56 阅读
  3. el-date-picker的使用

    2024-01-16 14:02:01       62 阅读
  4. openssl3.2 - 官方demo学习 - mac - siphash.c

    2024-01-16 14:02:01       56 阅读
  5. SQL Server查询优化方法

    2024-01-16 14:02:01       42 阅读
  6. hash 路由和 history 路由的区别

    2024-01-16 14:02:01       55 阅读
  7. js let 和 var 的区别

    2024-01-16 14:02:01       61 阅读
  8. Unix Network Programming Episode 84

    2024-01-16 14:02:01       36 阅读
  9. Leetcode刷题(二十四)

    2024-01-16 14:02:01       59 阅读
  10. 01-15网络编程-XML

    2024-01-16 14:02:01       48 阅读