链表的反转操作

以一个最简单的例子来展示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;
}
相关推荐
xiaolang_8616_wjl4 小时前
c++超级细致的基本框架
开发语言·数据结构·c++·算法
LYFlied5 小时前
【每日算法】LeetCode124. 二叉树中的最大路径和
数据结构·算法·leetcode·面试·职场和发展
yyy(十一月限定版)6 小时前
c语言——栈和队列
java·开发语言·数据结构
xu_yule7 小时前
算法基础-背包问题(01背包问题)
数据结构·c++·算法·01背包
蒙奇D索大7 小时前
【数据结构】考研408 | 伪随机探测与双重散列精讲:散列的艺术与均衡之道
数据结构·笔记·学习·考研
budingxiaomoli7 小时前
分治算法-快排
数据结构·算法
dragoooon347 小时前
[C++——lesson30.数据结构进阶——「红黑树」]
开发语言·数据结构·c++
蓝色汪洋8 小时前
数码串和oj
数据结构·算法
阿昭L9 小时前
leetcode链表是否有环
算法·leetcode·链表
yaoh.wang9 小时前
力扣(LeetCode) 83: 删除排序链表中的重复元素 - 解法思路
程序人生·算法·leetcode·链表·面试·职场和发展