206. Reverse Linked List

本文深入探讨了链表逆序的多种实现方法,包括迭代、递归和使用栈的方法。通过具体的代码示例,详细解释了每种方法的原理和步骤,为读者提供了丰富的实践指导。

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

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

python:

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre,cur=None,head
        while cur:
            temp=cur.next
            cur.next=pre
            pre=cur
            cur=temp
        return pre
        

C++循环:
在这里插入图片描述

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        
        ListNode* first = NULL;
        ListNode* second = head;
        ListNode* third = NULL;
        while(second){
            third = second->next;
            second->next=first;
            first=second;
            second=third;
        }
        return first;
    }
};

栈:

vector<int >printListFromTailToHead(struct ListNode* head)
{
std::stack<ListNode*> nodes;
ListNode* pNode=head;
while(pNode)
{
    nodes.push(pNode);
    pNode=pNode->next;
}
vector<int >res;
while(!nodes.empty())
{
    ListNode* temp=nodes.top();
    res.push_back(temp->val);
    nodes.pop();
}
return res;
}

递归:对当前结点的下一结点做递归,返回倒置后的链表,之后使当前结点的下一结点指向当前结点,当前结点指向NULL。

     ListNode* reverseList(ListNode* head)
     {
         if(head==NULL||head->next==NULL)
            return head;
            
         ListNode * nextNode=head->next;
         ListNode * res=reverseList(head->next);
         nextNode->next=head;
         head->next=NULL;
         return res;
     }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值