题解 | #链表的回文结构#
链表的回文结构
https://www.nowcoder.com/practice/d281619e4b3e4a60a2cc66ea32855bfa
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
// write code here
struct ListNode*head=A;
struct ListNode*p1=head->next;
struct ListNode*p2=p1->next;
if(A==NULL||A->next==NULL)
{
return true;
}
else if(A->next->next==NULL)
{
if(A->val==A->next->val)
{
return true;
}
else
{
return false;
}
}
while(p2)
{//我们要进行链表的逆置
if(A==head)
{
head->next=NULL;
}
p1->next=head;
head=p1;
p1=p2;
p2=p2->next;
}
p1->next=head;//完成逆置
head=p1;
while(A)
{
if(A->val!=head->val)
{
return false;
}
A=A->next;
head=head->next;
}
return true;
}
};
基恩士成长空间 452人发布