美文网首页
206. Reverse Linked List #Linked

206. Reverse Linked List #Linked

作者: LonelyGod小黄老师 | 来源:发表于2016-10-16 12:08 被阅读0次

    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

    相关文章

      网友评论

          本文标题:206. Reverse Linked List #Linked

          本文链接:https://www.haomeiwen.com/subject/lfgoyttx.html