每日算法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;
}
	
}
相关推荐
1000世界小札4 小时前
《大话数据结构》第9章精读:归并排序与快速排序完整 C++ 实现
数据结构·c++·算法
2601_956121977 小时前
背包基础篇(01、完全、分组、多重、混合)
c++·算法·动态规划
兴通物联科技8 小时前
SMT PCB 微小 DataMatrix 码扫不动问题分析 兴通 XT8601B 600 万像素工业读码器落地实践
大数据·人工智能·单片机·嵌入式硬件·算法·计算机视觉
月华路10 小时前
G1 GC 对数组与大对象(Humongous)的处理
java·jvm·算法
我想走路带风10 小时前
LRU和最长前缀和(计算机网络算法)
计算机网络·算法
M78佐菲11 小时前
Linux学习笔记:进程
linux·笔记·学习·算法
徐小夕12 小时前
表格、文档、甘特、大屏、表单一站打通:pxcharts超级表格4.0正式上线!
前端·算法·github
Xin77012 小时前
LeetCode 23.合并 K 个升序链表(分治递归)
leetcode
TechLee13 小时前
跨语言加解密总对不上?这个纯 Go 神库让 AES/RSA 与 PHP、Java 100% 互通
java·后端·算法