链表的反转操作

以一个最简单的例子来展示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;
}
相关推荐
crescent_悦3 小时前
PTA C++:正整数A+B
数据结构·c++·算法
丶小鱼丶3 小时前
数据结构和算法之【链表】
java·数据结构·算法
Frostnova丶4 小时前
LeetCode 1415. 长度为 n 的开心字符串中字典序第 k 小的字符串
数据结构·算法·leetcode
X-⃢_⃢-X4 小时前
二、索引的数据结构
数据结构·mysql
仰泳的熊猫5 小时前
题目2269:蓝桥杯2016年第七届真题-冰雹数
开发语言·数据结构·c++·算法·蓝桥杯
feng_you_ying_li5 小时前
list的介绍与底层实现
数据结构·c++·list
罗湖老棍子5 小时前
【例 3】校门外的树(信息学奥赛一本通- P1537)
数据结构·算法·树状数组
guguhaohao5 小时前
平衡二叉树(AVL),咕咕咕!
数据结构·c++·算法
一叶落4385 小时前
LeetCode 137. 只出现一次的数字 II —— 位运算解法
c语言·数据结构·算法·leetcode·哈希算法
像素猎人5 小时前
以数据结构之——树来体会深度优先搜索【dfs】和广度优先搜索【bfs】的妙用:学比特算法课的自用笔记
数据结构·c++·学习·dfs·bfs·深度优先搜索