LeetCode206——反转链表

一道经典的数据结构初学者问题,主要考察指针的修改和用法:
在这里插入图片描述
就像题目中进阶要求所说的那样,这道题有两种解法:迭代递归。但其实它们的核心操作都是一样的,就是代码中修改指针的部分,当然这题需要一前一后两个指针跟随着一步步将链表逆置。
下面贴出我的代码,首先是递归写法:

// recursive method
void recursive(ListNode*& Ahead, ListNode*& Follow)
{
    if(Ahead == nullptr)
        return;

    /*store the Ahead->next pointer*/
    ListNode* Tmp = Ahead->next;

    /*modify the pointer*/
    Ahead->next = Follow;
    Follow = Ahead;
    Ahead = Tmp;
        
    recursive(Ahead, Follow);
}

// start of the main function
ListNode* reverseList(ListNode* head)
{
    if(head == nullptr)
        return head;
            
    /*recursive method*/
    ListNode* Ahead = head->next;
    ListNode* Follow = head;

    /*set the first node's next to nullptr*/
    Follow->next = nullptr;

    recursive(Ahead, Follow);
    return Follow;
}

其次是迭代的写法:

ListNode* reverseList(ListNode* head) 
{
    if(head == nullptr)
        return head;

    /*iterative method*/
    ListNode* Ahead = head->next;
    ListNode* Follow = head;

    /*set the first node's next to nullptr*/
    Follow->next = nullptr;
    while(Ahead)
    {
        /*store the next pointer*/
        ListNode* Tmp = Ahead->next;

        Ahead->next = Follow;
        Follow = Ahead;
        Ahead = Tmp;
    }
    return Follow;
}

可以看到核心部分代码都是下面这几步,当然还有不要忘记将第一个结点的next指针指向nullptr:

 ListNode* Tmp = Ahead->next;
 Ahead->next = Follow;
 Follow = Ahead;
 Ahead = Tmp;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值