Leetcode #206 Reverse Linked List

Posted by blueskyson on March 28, 2022

Description

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]

Constraints:

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

Solution

1
2
3
4
5
6
7
8
9
10
struct ListNode* reverseList(struct ListNode* head){
    struct ListNode *next = NULL;
    while (head) {
        struct ListNode *tmp = head->next;
        head->next = next;
        next = head;
        head = tmp;
    }
    return next;
}

Runtime: 0 ms, faster than 100.00% of C online submissions for Reverse Linked List.

Memory Usage: 6.5 MB, less than 13.93% of C online submissions for Reverse Linked List.