1.先使用快慢指针求取链表的后一半
2.对后一半进行链表反转
3.前一半和后一半进行比较
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
//这里判断的是回文,不是环
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(NULL) {}
ListNode(int x) : val(x), next(NULL) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode * find(ListNode *head)
{
ListNode * slow = head;
ListNode * fast=head;
while(fast->next!=NULL&&fast->next->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
ListNode * reverse(ListNode *head)
{
ListNode *pre=NULL;
ListNode *post=NULL;
ListNode *p=head;
while(head!=NULL)
{
post=head->next;
head->next=pre;
pre=head;
head=post;
}
return pre;
}
int judge(ListNode *head1,ListNode *head2)
{
//这里要用后一半的指针判断,因为如果链表长度为奇数,前一半要比后一半多一个。
while(head2!=NULL)
{
if(head1->val!=head2->val) return 0;
head1=head1->next;
head2=head2->next;
}
return 1;
}
bool isPalindrome(ListNode* head) {
ListNode *p=head;
//利用快慢指针进行链表分段
ListNode *end=find(head);
// while(p)
// {
// cout<<p->val<<" ";
// p=p->next;
// }
// cout<<endl;
//翻转后半部分链表
ListNode * p1=NULL;
p1=reverse(end->next);
// cout<<"000000"<<endl;
// p=head;
//
//
// while(p)
// {
// cout<<p->val<<" ";
// p=p->next;
// }
//
// cout<<endl;
//进行判断
int flag=0;
flag=judge(head,p1);
if(flag) return true;
return false;
}
};
void build(ListNode *&head,int x)
{
if(head==NULL)
{
head=new ListNode(x);
return ;
}
else
{
ListNode *p=head;
while(p)
{
if(p->next==NULL)
{
p->next=new ListNode(x);
break;
}
p=p->next;
}
return ;
}
}
int main()
{
ListNode *head=NULL;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
// if(NULL==head)
// {
// head=new ListNode(x);
// continue;
// }
// else
// {
// ListNode *p=head;
// while(p)
// {
// if(p->next==NULL)
// {
// p->next=new ListNode(x);
// break;
// }
//
// p=p->next;
// }
// }
build(head,x);
}
ListNode *p=head;
while(p)
{
cout<<p->val<<" ";
p=p->next;
}
cout<<endl;
Solution a;
bool b=a.isPalindrome(head);
cout<<b;
}