每日算法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;
}
	
}
相关推荐
一去不复返的通信er4 小时前
力扣-图论-岛屿数量
算法·leetcode·图论
程序 代码狂人7 小时前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
HDU-Dade8 小时前
【校招笔试真题】简要介绍 Self-Attention 的前沿算法
人工智能·算法
Xin7709 小时前
LeetCode 79. 单词搜索(DFS 回溯法)
leetcode
Zwawa9 小时前
编译器工具链:GCC、Clang、MSVC、ICC、armclang
c语言·嵌入式·编译器
学逆向的9 小时前
C 指针常量与常量指针
c语言·开发语言·网络安全
水饺编程10 小时前
第2章:Linux 基础,exit 命令
linux·c语言·汇编
小郎君65810 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
算法
邵奈一10 小时前
GPT-6.1 Terra速度是Sol的3倍,价格减半
算法
RaaS10010 小时前
Node.js Brotli RCE 漏洞自查指南:fetch、undici、axios 都在影响面,三分钟确认你的版本
人工智能·深度学习·算法