leetcode 206 反转链表

第一个自己写的递归,虽然执行时间很长,但已经是巨大进步了。贴代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution 
{
public:
    ListNode* reverseList(ListNode* head) 
    {
        if(!head || !head->next)
        {
            return head;
        }
        else
        {
            ListNode* temp = reverseList(head->next);
            ListNode* temp1 = temp;
            while(temp->next)
            {
                temp = temp->next;
            }
            temp->next = head;
            head->next = NULL;
            return temp1;
        }
        
    }
};

擦,人家的递归就是不一样,简洁易懂,nnd,贴代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution 
{
public:
    ListNode* reverseList(ListNode* head) 
    {
        if(!head || !head->next)
        {
            return head;
        }
        else
        {
            ListNode* temp = reverseList(head->next);
            head->next->next = head;
            head->next = NULL;
            return temp;
        }
        
    }
};

擦,发现自己的方法和官方的思路一样,只是最后一步,效率很差,究其原因,是因为图画的不好,较好的方式是不改变元素的相对位置,只改变箭头的方向,这样就一目了然了。

posted @ 2021-02-09 16:27  zhaohhhh  阅读(49)  评论(0)    收藏  举报