美文网首页
206 reverse linked list

206 reverse linked list

作者: larrymusk | 来源:发表于2017-11-20 20:26 被阅读0次

    两种方法 一种迭代 一种递归 都需要熟练掌握

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* reverseList(struct ListNode* head) {
        if(head == NULL)
            return NULL;
        if(head->next == NULL)
            return head;
        struct ListNode *node;
    
        node = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
    
        return node;    
    }
    
    struct ListNode* reverseList(struct ListNode* head) {
        if(head == NULL || head->next == NULL)
            return head;
        struct ListNode *prev, *curr, *next;
        curr = head;
        prev = NULL;
        next = NULL;
        while(curr){
            next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
    
        return prev;    
    }
    

    相关文章

      网友评论

          本文标题:206 reverse linked list

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