C语言笔记32 •单链表经典算法OJ题-4.查找链表的中间结点•

1.问题

给你单链表的头结点 head ,请你找出并返回链表的中间结点。

如果有两个中间结点,则返回第二个中间结点。

2.代码实现(快慢指针)

cpp 复制代码
//4.查找链表的中间结点
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>


typedef int SLTDataType;

typedef struct SListnode
{
	SLTDataType val;
	struct SListnode* next;
}ListNode;

ListNode* createNode(SLTDataType val)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(1);
	}
	newnode->val = val;
	newnode->next = NULL;
	return newnode;
}



struct ListNode* middleNode(struct ListNode* head)
{
	if (head == NULL)
	{
		return head;
	}
	ListNode* slow, * fast;
	slow = fast= head;
	while (fast && fast->next)
	{
		slow = slow->next;
		fast = fast->next->next;
	}
	return slow;
}

int main()
{
	ListNode* node1, * node2, * node3, * node4, * node5, * node6;

	node1 = createNode(1);
	node2 = node1->next = createNode(2);
	node3 = node2->next = createNode(3);
	node4 = node3->next = createNode(4);
	node5 = node4->next = createNode(5);
	//node6 = node5->next = createNode(6);//创建一个链表

	ListNode* node = middleNode(node1);
	printf("%d", node->val);

	return 0;
}
相关推荐
辰海Coding6 小时前
MiniSpring框架学习笔记-解决循环依赖的简化IoC容器
笔记·学习
晓梦林7 小时前
cp520靶场学习笔记
android·笔记·学习
心中有国也有家8 小时前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
玄米乌龙茶1238 小时前
LLM成长笔记(三):API 开发基础
笔记
Upsy-Daisy8 小时前
AI Agent 项目学习笔记(八):Tool Calling 工具调用机制总览
人工智能·笔记·学习
绝知此事8 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
碧海银沙音频科技研究院8 小时前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
csdn_aspnet9 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
LuminousCPP9 小时前
数据结构 - 线性表第四篇:C 语言通讯录优化升级全记录(踩坑 + 思考)
c语言·开发语言·数据结构·经验分享·笔记·学习