NC78 #反转链表#

反转链表

http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

解法一:双指针
注意点:left要初始化为NULL

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* left = NULL, *right = pHead;
        while(right)
        {
            ListNode* temp = right->next;
            right->next = left;
            left = right, right = temp;
        }
        return left;
    }
};

解法二:递归

class Solution {
public:
    ListNode* dfs(ListNode* pre, ListNode* now)
    {
        if(!now) 
            return pre;
        ListNode* temp = now->next;
        now->next = pre;
        return dfs(now, temp);
    }
    ListNode* ReverseList(ListNode* pHead) {
        return dfs(nullptr, pHead);
    }
};

不知道为什么这样写就会堆栈溢出:

class Solution {
public:
    ListNode* dfs(ListNode* pre, ListNode* now)
    {
        ListNode* temp = now->next;
        now->next = pre;
        if(temp)
            return dfs(now, temp);
        else
            return now;
    }
    ListNode* ReverseList(ListNode* pHead) {
        return dfs(nullptr, pHead);
    }
};
全部评论

相关推荐

LZHR:老哥你从投递简历测评完到一面中间隔了多久呀,我这边已经过了五天了仍显示简历筛选中是不是就是挂了
腾讯求职进展汇总
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务