反转链表

这道题是一道基础题目,运用递归比较直观,运用迭代比较节约资源。
方法1递归:
对于每一个链表头,对它的next节点链接的链表进行翻转,调用reverse(head->next)就能在递归之后得到一个翻转过的链表,此时将原头节点插入反转过后的尾节点即可。

 ListNode* reverseList(ListNode* head) {        
        if(head!=nullptr&&head->next!=nullptr)
        {
            ListNode* now=head;
            ListNode* temp=reverseList(head->next);
            now->next=nullptr;
            head=temp;
            while(temp->next!=nullptr)
                temp=temp->next;
            temp->next=now;
            return head;         
        }
        return head;
    }

方法2迭代:
相对递归而言不算直观,思路基本上是将当前节点的下一个节点移动到当前节点的前面,直到当前节点next域为空。

ListNode* reverseList(ListNode* head) { 
if(head==nullptr||head->next==nullptr)
        return head;
    ListNode* truehead=head;
    while(head->next!=nullptr)
    {ListNode*temp=head;
    temp=temp->next;
    head->next=temp->next;
    temp->next=truehead;
    truehead=temp;}
    return truehead;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值