每日算法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;
}
	
}
相关推荐
手写码匠2 小时前
华为云Flexus+DeepSeek征文|Dify 构建企业级联网搜索 Agent:查询改写、多源检索与引用溯源实战
人工智能·深度学习·算法·aigc
七夜zippoe2 小时前
DolphinDB 能耗统计分析实战:报表生成、同比环比与定额对比
人工智能·算法·dolphindb·报表生成·能耗统计·定额对比
为啥全要学2 小时前
在大语言模型上使用 PPO 算法
人工智能·算法·语言模型
Nebula嵌入式2 小时前
【C语言】01-从零开始:编译运行与第一个程序
c语言·嵌入式
zander2582 小时前
35. 搜索插入位置:从边界语义理解二分查找
数据结构·算法·leetcode
汤愈韬3 小时前
模型求解算法
人工智能·算法·机器学习
Keven_113 小时前
算法札记:DP中的滚动数组
算法·滚动数组
luj_17683 小时前
随机性在算法与占卜中的共通原理
c语言·开发语言·c++·经验分享·算法
yyds_yyd_100863 小时前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode