206. Reverse Linked List(迭代+递归)

首刷自解(类似于在链表的头上插入节点) 迭代

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* reverseList(struct ListNode* head){
    struct ListNode* H=(struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* ptr;
    H->next=NULL;
    while(head)
    {
        ptr=head;
        head=head->next;
        ptr->next=H->next;
        H->next=ptr;
    }
    return H->next;
}

无哨兵节点解法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* reverseList(struct ListNode* head){
    struct ListNode* pre=NULL;
    struct ListNode* cur=head;
    while(cur)
    {
        struct ListNode* next=cur->next;
        cur->next=pre;
        pre=cur;
        cur=next;
    }
    return pre;
}

首刷递归自解(error:返回的始终都是第一个节点 例:1<-2<-3返回的始终是1所对应的那个节点)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* reverseList(struct ListNode* head){
    if(head==NULL||head->next==NULL)
    return head;
    head->next=reverseList(head->next);
    head->next->next=head;
    head->next=NULL;
    return head;
}

官解
在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* reverseList(struct ListNode* head){
    if(head==NULL||head->next==NULL)
    return head;
    struct ListNode* NewHead=reverseList(head->next);//重点:关于Newhead的理解 递归一层一层入栈 开始出栈时 NewHead0指向最后一个节点然后return NewHead0,使得下层的NewHead1指向NewHead0 然后return NewHead1,使得下层的NewHead2指向NewHead1,以此类推,最终返回的NewHeadN是指向原链表的最后一个节点的,也就是反转后链表的第一个节点,上图与之对应!
    head->next->next=head;
    head->next=NULL;//head->next=head->next->next error:指回了自己本身 例:1->2->3->4 本条语句不能跟上条语句调换位置 否则head->next==NULL  head->next->next就会发生错误
    return NewHead;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值