leetCode 206. Reverse Linked List

本文深入探讨了经典链表反转问题,通过迭代和递归两种方法实现,并详细解析了每种方法的原理与代码实现。此外,还介绍了使用栈实现反转链表的方法,展示了递归本质上是一种特殊的栈操作。

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

        题目链接:https://leetcode.com/problems/reverse-linked-list/

        题目内容:

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

        题目分析:

        就是经典的反转链表啦~题目的提示还说用迭代和递归都实现一遍,我只实现了迭代的写法,递归的网上很多,引用其中一位(作者:云中孤鹜)。然后第三种写法是使用栈实现的,虽然消耗多余的空间,但是递归本质上也是一种栈。

        递归的写法:

//递归方式
ListNode * ReverseList2(ListNode * head)
{
	//如果链表为空或者链表中只有一个元素
	if(head==NULL || head->m_pNext==NULL)
		return head;
	else
	{
	   ListNode * newhead=ReverseList2(head->m_pNext);//先反转后面的链表
	   head->m_pNext->m_pNext=head;//再将当前节点设置为其然来后面节点的后续节点
	   head->m_pNext=NULL;
	   return newhead;
	}
}
        迭代的写法:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == NULL)
            return NULL;
        else {
            ListNode* pre = NULL;
            ListNode* cur = head;
            
            while(cur->next != NULL) {
                ListNode* pNext = cur->next;
                cur->next = pre;
                pre = cur;
                cur = pNext;
            }
            cur->next = pre;
            return cur;
        }
    }
};
        使用STL栈实现的写法:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == NULL)
            return NULL;
     
        stack<ListNode*> nodes;
    	ListNode* lists = head;
    	while (lists->next != NULL)
    	{
    		nodes.push(lists);
    		lists = lists->next;
    	}
    
    	ListNode* newpHead = lists;
    	ListNode* newLists = newpHead;
    	while (!nodes.empty())
    	{
    		newLists->next = nodes.top();
    		newLists = newLists->next;
    		nodes.pop();
    	}
    	newLists->next = NULL;
    	return newpHead;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值