206. Reverse Linked List

本文探讨了三种不同的链表反转方法:一种导致超时的迭代方法、一种通过新建头节点实现的迭代方法以及递归方法。文章提供了详细的代码示例并解释了每种方法的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


  • 思路1

自己想的,结果是超时,为什么会超时 >_<


class Solution {
public:
    ListNode* reverseList(ListNode* head) {

        ListNode* next=NULL;
        ListNode* nhead=head;

        while(head && head->next)
        {
            next = head->next;
            head->next = next->next;
            nhead = next;
            next->next = nhead;
        }
        return nhead;
    }
};

  • 思路2

创建一个新的头节点0,指向head
最后返回的时候直接用新的头节点的next

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* new_head = new ListNode(0);
        new_head -> next = head;
        ListNode* pre = new_head;
        ListNode* cur = head; 
        while (cur && cur -> next) {
            ListNode* temp = pre -> next;
            pre -> next = cur -> next;
            cur -> next = cur -> next -> next; 
            pre -> next -> next = temp;
        }
        return new_head -> next;
    }
};

  • 思路3
    递归
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值