面试题24:反转链表(非递归+递归)

1、非递归版
三指针,保留当前的下一个节点,将当前节点的m_Next指向前一个节点,前一个节点移动到当前节点,当前节点移动到下一个节点

#include<iostream>

struct listNode
{
	int m_nValue;
	listNode* m_Next;
	listNode(int _value):m_nValue(_value){}
};


listNode* ReverseList(listNode* pHead)
{
	listNode* pReverseHead = nullptr;
	listNode* pNode = pHead;
	listNode* pPre = nullptr;
	while (pNode)
	{
		listNode* pNext = pNode->m_Next;
		if (pNext == nullptr)
			pReverseHead = pNode;
		pNode->m_Next = pPre;
		pPre = pNode;
		pNode = pNext;
	}
	return pReverseHead;
}

2、递归版

m_ListNode* ListOfSingle::ReverseList(m_ListNode* pHead)
{
	if (pHead == nullptr || pHead->next == nullptr)
		return pHead;//找到最后一个节点,作为结束条件
	m_ListNode* newHead = ReverseList(pHead->next);//最后一个节点为新得头节点
	pHead->next->next = pHead;//当前节点的下一个节点指向当前节点
	pHead = nullptr;//当前节点为空
	return newHead;//返回新头节点
}
发布了107 篇原创文章 · 获赞 28 · 访问量 1967

猜你喜欢

转载自blog.csdn.net/qq_38994205/article/details/104396654