Leetcode 206. Reverse Linked List

Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?

s思路:
1. 要求iterative和recursive.
2. 先来iterative。iterative写过几次了,简单的就是用dummy,然后pre,pnow,pnext三个指针不停移动,交换!写完发现,dummy都省了,直接三个指针移位和交换就搞定了!
3. 再来recursive:
这里写图片描述
x需要注意的是:代码写完后,检查在结尾的地方,也就是链表两头是否因为少了对指针清零等操作导致的cycle。如上图,就是1->2之间的指针没有清零,而2->1又建立起来,于是cycle!

//方法1:iterative.搞了半天,居然都不用加dummy。直接返回尾指针!
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        /*ListNode node(0);
        ListNode* dummy=&node;
        dummy->next=head;*/
        ListNode* pre=NULL,*pnow=head,*pnext=NULL;
        while(pnow){
            pnext=pnow->next;
            pnow->next=pre;
            if(!pnext) return pnow;
            pre=pnow;
            pnow=pnext;
        }
        return NULL;
    }
};


//方法2:recursive:
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head) return NULL;
        if(!head->next) return head;
        ListNode* tail=head->next;

        ListNode* newhead=reverseList(head->next);
        tail->next=head;
        head->next=NULL;//bug:没有这一句,就cycle.加上这一句,就cycle free
        return newhead;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值