链表的反转操作

以一个最简单的例子来展示C语言中链表的反转操作。

首先是利用结构体功能实现链表这一种数据结构,它拥有自身的成员属性(这里以一个int型数据为例)和一个指向下一个链表节点的指针组成。注意这里typedef的使用方法,结构体内部嵌套自身的时候还不能将struct ListNode简写为ListNode。

cpp 复制代码
typedef struct ListNode {
	int data;
	struct ListNode* next;
}ListNode;

其次是链表的创建函数, 在堆中开辟内存空间用于存贮链表节点。

cpp 复制代码
ListNode* createNode(int newData)
{
	ListNode* newNode=(ListNode *)malloc(sizeof(ListNode));
	if (newNode == NULL)
	{
		printf("内存分配失败");
		exit(1);
	}

	newNode->data = newData;
	newNode->next = NULL;

	return newNode;
}

再然后尝试打印链表节点中存贮的数据,新建一个临时变量,在while循环内一次打印链表内所有数据,直到当前节点的下一节点指向空指针。

cpp 复制代码
void printfNode(ListNode* head)
{
	ListNode* temp = head;
	while (temp != NULL)
	{
		printf("%d ",temp->data);
		temp = temp->next;
	}
	printf("\n");
}

反转链表的操作如注释所言。

cpp 复制代码
ListNode* reserveNode(ListNode* head)
{
	//声明三个局部变量,相当与空的容器
	ListNode* prev = NULL;
	ListNode* current = head;
	ListNode* nextNode = NULL;

	while (current!=NULL)
	{
		nextNode = current->next; //保存当前节点指向的下一节点
		current->next = prev;     //令当前节点指向上一个节点

		prev = current;
		current = nextNode;
	}

	return prev;
}

整体测试代码:

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>

typedef struct ListNode {
	int data;
	struct ListNode* next;
}ListNode;

ListNode* createNode(int newData)
{
	ListNode* newNode=(ListNode *)malloc(sizeof(ListNode));
	if (newNode == NULL)
	{
		printf("内存分配失败");
		exit(1);
	}

	newNode->data = newData;
	newNode->next = NULL;

	return newNode;
}

void printfNode(ListNode* head)
{
	ListNode* temp = head;
	while (temp != NULL)
	{
		printf("%d ",temp->data);
		temp = temp->next;
	}
	printf("\n");
}

ListNode* reserveNode(ListNode* head)
{
	//声明三个局部变量,相当与空的容器
	ListNode* prev = NULL;
	ListNode* current = head;
	ListNode* nextNode = NULL;

	while (current!=NULL)
	{
		nextNode = current->next; //保存当前节点指向的下一节点
		current->next = prev;     //令当前节点指向上一个节点

		prev = current;
		current = nextNode;
	}

	return prev;
}


int main()
{
	ListNode* head = createNode(1);//头节点里面存储了1
	head->next= createNode(2);
	head->next->next = createNode(3);
	head->next->next->next = createNode(4);

	printf("原始链表:");
	printfNode(head);
	ListNode* resehead=reserveNode(head);
	printf("反转链表:");
	printfNode(resehead);

	return 0;
}
相关推荐
想睡hhh31 分钟前
c++进阶——哈希表的实现
开发语言·数据结构·c++·散列表·哈希
打鱼又晒网2 小时前
数据类型:List
数据结构·list
java程序员CC2 小时前
记录为什么LIst数组“增删慢“,LinkedList链表“查改快“?
数据结构·链表·list
.格子衫.3 小时前
015枚举之滑动窗口——算法备赛
数据结构·算法
虾球xz8 小时前
游戏引擎学习第268天:合并调试链表与分组
c++·学习·链表·游戏引擎
jiunian_cn12 小时前
【c++】异常详解
java·开发语言·数据结构·c++·算法·visual studio
康康这名还挺多14 小时前
鸿蒙HarmonyOS list优化一: list 结合 lazyforeach用法
数据结构·list·harmonyos·lazyforeach
Helibo4414 小时前
GESPC++六级复习
java·数据结构·算法
EnticE15214 小时前
[高阶数据结构]二叉树经典面试题
数据结构·算法·面试
_星辰大海乀15 小时前
数据库约束
java·数据结构·数据库·sql·链表