Reverse Linked List

Description

Reverse a linked list.

Example
For linked list 1->2->3, 
the reversed linked list is 3->2->1

Challenge
Reverse it in-place and in one-pass

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
/**
 * Definition of ListNode
 * 
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 * 
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The new head of reversed linked list.
     */
    // --------------------------------------------------
    // iterator version 
    ListNode *reverse(ListNode *head) {
        // write your code here
        if (!head) {
            return nullptr;
        }
        ListNode* cur = nullptr;
        while (head) {
            ListNode* tmp = head->next;
            head->next = cur;
            cur = head;
            head = tmp;
        }
        return cur;
    }
    // ----------------------------------------------------
    // recursive version
    ListNode* reverse(ListNode* head) {
        if (!head) {
            return nullptr;
        }
        return helper(head, nullptr);
    }
    ListNode* helper(ListNode* head, ListNode* tail) {
        if (!head) {
            return tail;
        }
        ListNode* tmp = head->next;
        head->next = tail;
        tail = head;
        return helper(tmp, tail);
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""