206. Reverse Linked List #Linked

2016-10-16  本文已影响0人  LonelyGod小黄老师

Problem:

Reverse a singly linked list.

Solution:

//my solution
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == NULL || head->next == NULL) return head;
        ListNode* it = head;
        ListNode* prev = NULL;
        ListNode* next = it->next;
        while(1)
        {
            it->next = prev;
            prev = it;
            it = next;
            if(it == NULL) break;
            next = it->next;
        }
        head = prev;
        return head;
    }
};
//recursion solution
class Solution {
public:   
    ListNode* reverseList(ListNode* head) {
        if (!head || !(head -> next)) return head;
        ListNode* node = reverseList(head -> next);
        head -> next -> next = head;
        head -> next = NULL;
        return node; 
    }
}; 

LeetCode Discussion

上一篇下一篇

猜你喜欢

热点阅读