牛客题霸-反转链表题解

反转链表

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=117&&tqId=35000&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking

反转链表:https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=117&&tqId=35000&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking

1、借助三个临时节点pre,cur,after进行迭代。

class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
    if (pHead == nullptr || pHead->next == nullptr) return pHead;
    ListNode * pre = nullptr,*cur = pHead,*after = pHead->next;
    while(cur != nullptr){
        cur->next = pre;
        pre = cur;
        cur = after;
        if(after != nullptr)
            after = after->next;
    }
    return pre;
}
};

2、头插法来做,将元素开辟在栈上,这样会避免内存泄露

ListNode* ReverseList(ListNode* pHead) {

    // 头插法
    if (pHead == nullptr || pHead->next == nullptr) return pHead;
    ListNode dummyNode = ListNode(0);
    ListNode* pre = &(dummyNode);
    pre->next = pHead;
    ListNode* cur = pHead->next;
    pHead->next = nullptr;
    //pre = cur;
    ListNode* temp = nullptr;
    while (cur != nullptr) {
        temp = cur;
        cur = cur->next;
        temp->next = pre->next;
        pre->next = temp;
    }
    return dummyNode.next;

}

个人更喜欢第二种方法,但是第一种更好理解一点哈

全部评论
楼主的方法很不错,我个人也同意第一种的方法更好理解。
2 回复 分享
发布于 2020-11-06 16:23

相关推荐

不愿透露姓名的神秘牛友
07-11 17:10
什么素质,我请问呢,要掉小珍珠了。。。又憋屈又生气
苍蓝星上艾露:给它们能的,一群dinner牛马挥刀向更弱者罢了。我写的开源求职AI co-pilot工具,优化你的简历,找到你匹配的岗位,定制你的简历,并让你做好面试准备https://github.com/weicanie/prisma-ai
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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