思路:
找中间节点–>逆置->比较文章来源:https://www.toymoban.com/news/detail-731056.html
代码:文章来源地址https://www.toymoban.com/news/detail-731056.html
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* middleNode(struct ListNode* head)
{
struct ListNode*slow=head;
struct ListNode*flast=head;
while(flast&&flast->next)
{
slow=slow->next;
flast=flast->next->next;
}
return slow;
}
struct ListNode* reverseList(struct ListNode* head){
struct ListNode*newhead=NULL;
struct ListNode*cur=head;
while(cur)
{
struct ListNode*per=cur->next;
cur->next=newhead;
newhead=cur;
cur=per;
}
return newhead;
}
bool isPalindrome(struct ListNode* head){
struct ListNode* mid=middleNode(head);//找中间节点
struct ListNode* rmid=reverseList(mid);//逆置
//比较
while(head&&rmid)
{
if(head->val==rmid->val)
{
head=head->next;
rmid=rmid->next;
}else {
return false;
}
}
return true;
}
到了这里,关于链表的回文判断的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!