每日算法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;
}
	
}
相关推荐
susplus4 小时前
【传感器DS18B20】51单片机上实现温度采集
c语言·51单片机·ds18b20·温度采集
荆棘鸟智能4 小时前
无人机遥感图像实时拼接算法工程实践:从特征提取到全景融合的完整技术链路
算法·无人机
xxwxx__4 小时前
C++ STL set 与 map 全套详解:关联式容器、红黑树底层、代码坑点、刷题实战
数据结构·c++
6Hzlia4 小时前
【Classic 150 刷题计划】 LeetCode 58. 最后一个单词的长度 | C++ 极简反向遍历与单变量状态机
算法
AgentMaster5 小时前
企业如何应用智能客服?5 个典型场景的技术架构与实施路径
大数据·算法
程曦曦5 小时前
MySQL 生产库误删 98 张表后的时间点恢复实战:从 binlog 解析到资金对账
linux·数据结构·其他·算法·ubuntu·运维开发
郝学胜-神的一滴5 小时前
Effective Python 条款 13:善用星号解包,告别下标切片拆分的坑
服务器·开发语言·数据结构·python·程序人生·pycharm
Logic1015 小时前
C语言/数据结构位运算题解:异或XOR找出流水线上的“独特零件编号“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
山下梅子酒2255 小时前
洛谷-入门-B2043
c语言
weixin_307779136 小时前
C++代码实现MATLAB中的ode45函数功能
开发语言·c++·算法·matlab