leetcode 206 反转链表I

本文详细解析了链表逆置的两种实现方式:迭代和递归。通过具体代码示例,展示了如何通过调整指针顺序来达到逆置链表的目的。适用于初学者理解和掌握链表逆置的基本原理。

Example:
Input: 1->2->3->4->5->NULL
Output : 5->4->3->2->1->NULL
Follow up :
A linked list can be reversed either iteratively or recursively.Could you implement both ?

如果这个链表存在头结点,可以将头结点摘下来,然后从第一结点开始,依次插入到头结点后面,即采用头插法建立单链表的思想,直到最后一个结点为止,这样就实现了链表的逆置。

ListNode* reverseList(ListNode* head) {
	ListNode* cur = head->next;
	head->next = nullptr;
	while (cur != nullptr)
	{
		ListNode* next = cur->next;
		cur->next = head->next;
		head->next = cur;
		cur = next;
	}
	return head;
}

然而题目中的链表并没有头结点,所以第一个结点就要考虑特殊处理,思路是相同的

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre = nullptr;
        ListNode* cur = head;
        while(cur != nullptr)
        {
            ListNode* next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
};

递归代码,leetcode题解

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head->next == nullptr)
        {
            return head;
        }
        ListNode* last = reverseList(head->next);
        head->next->next = head;
        head->next = nullptr;
        return last;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值