每日算法day3—回文链表,链表分割

第一题:

给定一个链表的 头节点 head ,请判断其是否为回文链表。
如果一个链表是回文,那么链表节点序列从前往后看和从后往前看是相同的。

示例 1:

输入: head = 1,2,3,3,2,1

输出: true

示例 2:

输入: head = 1,2

输出: false

解题思路:找到中间节点,并将中间节点及之后的链表进行反转,依次遍历。

c 复制代码
struct ListNode*relimove(struct ListNode*head)
{
	if(head==NULL)
		return NULL;
	struct ListNode*pcur=head;
	struct ListNode*next=pcur->next;
	struct ListNode*newhead=NULL;
	while(pcur)
	{
		if(newhead==NULL)
		{
			newhead=pcur;
			newhead->next=NULL;
		}
		else
		{
			pcur->next=newhead;
			newhead=pcur;
		}
		pcur=next;
		if(next)
			next=next->next;
	}	
}
bool isPalindrome(struct ListNode* head)
{
	struct ListNode*slow=head;
	struct ListNode*fast=head;
	while(fast&&fast->next)
	{
		slow=slow->next;
		fast=fast->next->next;
	}
	//走到这就表示找到了开始反转中间节点及之后的链表
	struct ListNode*pcur=relimove(slow);
	struct ListNode*cur=head;
	while(pcur)//pcur会比cur先走完
	{
		if(pcur->val!=cur->val)
			return false;
		pcur=pcur->next;
		cur=cur->next;
	}
	return true;//一旦走完就表示是回文
	

第二问:
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
你不需要 保留 每个分区中各节点的初始相对位置。

解题思路:创建两个大小头节点,小头节点负责存放小于 x 的节点,大头节点存放大于或等于 x 的节点再将两个节点连接起来即可。

c 复制代码
struct ListNode* partition(struct ListNode* head, int x)
{
	if(head==NULL)
		return NULL;
	struct ListNode*pcur=head;
	struct ListNode*lesshead=NULL;
	struct ListNode*less=NULL;
	less=lesshead=(struct ListNode*)malloc(sizeof(struct ListNode));
	struct ListNode*bighead=NULL;
	struct ListNode*big=NULL;
	big=bighead=(struct ListNode*)malloc(sizeof(struct ListNode));
	while(pcur)
	{
		if(pcur->val<x)
		{
			less->next=pcur;
			less=less->next;
		}
		else
		{
			big->next=pcur;
			big=big->next;
		}
		pcur=pcur->next;
	}
	big->next=NULL;//避免出现末尾指针出现死循环
	less->next=bighead->next;//小节点末尾指针指向大节点的真正指针。
	struct ListNode*ret=lesshead->next;//哨兵位的下一个节点为真正节点
	free(lesshead);
	free(bighead);
	return ret;
}
	
}
相关推荐
罗湖老棍子3 小时前
Biorhythms(信息学奥赛一本通- P1639)
算法·数论·裴蜀定理·扩展欧几里得·扩展中国剩余定理
奋发向前wcx8 小时前
CSP-J复赛模拟赛4 王晨旭补题 2026.10.5
算法
念何架构之路11 小时前
zap采样器与性能优化内幕
算法·性能优化·哈希算法
晒太羊的猫11 小时前
hot100动态规划刷题
算法·动态规划
weixin_5310946912 小时前
heap_4内存管理
java·开发语言·算法
余额瞒着我当琳12 小时前
红黑树的实现--红黑树的概念、规则、效率、结构、旋转、查找、验证
数据结构·c++·算法
程序员南飞12 小时前
win系统安装minio
java·数据结构·算法
青少儿编程课堂12 小时前
AC自动机多模式串匹配精讲:校园关键词巡检实战解析
c++·python·算法·bfs·信息学竞赛
longlongzihan13 小时前
LeetCode 5. 最长回文子串:从暴力匹配到中心扩展的思维演进
c++·算法·leetcode
waoooqwe13 小时前
问卷样本真实吗
大数据·数据库·算法·数据分析