前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【C++】链表反转

【C++】链表反转

作者头像
DevFrank
发布2024-07-24 15:04:59
730
发布2024-07-24 15:04:59
举报
文章被收录于专栏:C++开发学习交流

链表反转是C++面试经常会考的一道题目,下面介绍2种解法,分别是非递归法和递归法。

理论

1.非递归法(迭代反转) 创建3个指针pre cur nex,每个循环指针各向后移动一个节点。

2.递归法 通过不断压栈,然后退栈,先进后出。

代码实现

代码语言:javascript
复制
//test 反转链表

#include <iostream>
using namespace std;

struct ListNode
{
	int val;
	ListNode *next;
};

//打印链表
void printList(ListNode* head)
{
	while (head)
	{
		cout << head->val;
		head = head->next;
		if (head)
			cout << "->";
	}
	cout << "\n";
}

//反转链表
//1.非递归法
ListNode* reverseList1(ListNode* head)
{
	//初始化ListNode
	ListNode *pre = NULL;
	ListNode *cur = head;
	ListNode *nex = NULL;

	while (cur)
	{
		//当前链表非空,进行以下处理
		nex = cur->next;	//当前值的下一位
		cur->next = pre;
		pre = cur;	//当前值赋给pre
		cur = nex;	//下一位赋给当前值
	}
	return pre;
}

//2.递归法
ListNode* reverseList2(ListNode* head)
{
	if ( !head || !head->next)
		return head;
	ListNode *pNode = reverseList2(head->next);
	head->next->next = head;
	head->next = NULL;
	return pNode;
}

//main
int main()
{
	//创建链表
	ListNode* head = NULL;
	ListNode* cur = NULL;	//current
	for (int i = 1; i <= 6; ++i)
	{
		ListNode* node = new ListNode;
		node->val = i;
		node->next = NULL;
		if (head == NULL)
		{
			head = node;
			cur = node;
		}
		else
		{
			cur->next = node;
			cur = node;
		}
	}
	printList(head);	//打印当前链表
	printList(reverseList1(head));	//第一种方法
	//printList(reverseList2(head));	//第二种方法
	return 0;
}

运行结果如下:

在这里插入图片描述
在这里插入图片描述

以上。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-11-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 理论
  • 代码实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档