Saturday, July 9, 2016

Reverse Linked List

Reverse a singly linked list.

Solution:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        /*
        // Iterative.
        if (head == NULL)
            return head;
        ListNode *next = NULL, *pre = NULL, *curr = head;
        while (curr != NULL) {
            next = curr -> next;
            curr -> next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
        */
        // Recursive.
        if (head == NULL || head -> next == NULL) {
            return head;
        }
        ListNode *end = NULL;
        end = reverseList(head -> next);
        head -> next -> next = head;
        head -> next = NULL;
        return end;
    }
};

No comments:

Post a Comment