Reverse Linked List

07/16/2016 Linked List

Question

Reverse a singly linked list.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?


Solution

Result: Accepted Time: 0 ms

Here should be some explanations.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode * top = NULL,* tmp;
    while(head)
    {
        tmp = head->next;
        head->next = top;
        top = head;
        head = tmp;
    }
    return top;
}

Complexity Analytics

  • Time Complexity:
  • Space Complexity: