题目:
给定一个链表的头结点head,判断该链表是否为回文结构
例如:
1->2->3->2->1 返回 true;
1->2->3 ->2返回 false; 要求时间复杂度为O(n),空间复杂度为O(1);
这道题目不能另设一个栈空间,只能通过链表标记指针将链表后半部分 逆序,在比较 相等为回文链表 不同返回false;
需要注意的是最后需要回复链表为之前的状态
1.这里代码中需要使用两次头插法
2.使用两个指针n1,n2分别充当慢指针n1和快指针n2,慢指针走一步,快指针走两步,当快指针走到链表结尾时,慢指针到达链表中间位置
代码:(注释比较详细)
#include <cstdio>
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *next;
};
bool isPalindrome(node *head)
{
if (head == NULL || head->next == NULL)
{
return true;
}
//for text 输出链表测试当前链表的状态
cout << "改变前:" << endl;
node *p = head;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
//-------------------------
node *n1 = head;//yibu
node *n2 = head;//liangbu
while (n2->next != NULL&&n2->next->next != NULL)
{
n1 = n1->next;
n2 = n2->next->next;
}//循环结束n1指向中间结点n2指向结尾结点
n2 = n1->next;
n1->next = NULL;
node *n3 = NULL;
while (n2 != NULL)//头插法逆序
{
n3 = n2->next;
n2->next = n1->next;
n1->next = n2;
n2 = n3;
}
//for text 输出链表测试当前链表的状态
cout << "改变后:" << endl;
node *p1 = head;
while (p1 != NULL)
{
cout << p1->data << " ";
p1 = p1->next;
}
cout << endl;
//-------------------------
n2 = head;
n3 = n1;//记录中点便于还原链表
n1 = n1->next;//n1指向后半部分第一个结点
bool res = true;
while (n1 != NULL)//进行比较半段是否为回文
{
if (n1->data != n2->data)
{
res = false;
break;
}
n2 = n2->next;
n1 = n1->next;
}
n2 = n3->next;//n2指向后半部分第一个结点
n1 = n3;//n1指向中点
n1->next = NULL;
while (n2 != NULL)//头插法对链表进行还原
{
n3 = n2 -> next;
n2->next = n1->next;
n1->next = n2;
n2 = n3;
}
//for text 输出链表测试当前链表的状态
cout << "恢复后:" << endl;
node *p2 = head;
while (p2 != NULL)
{
cout << p2->data << " ";
p2 = p2->next;
}
cout << endl;
//-------------------------
return res;
}
int main()
{
node *head1, *head2;
head1 = new node;
head1->data = 1;
head1->next = new node;
head1->next->data = 2;
head1->next->next = new node;
head1->next->next->data = 3;
head1->next->next->next = new node;
head1->next->next->next->data = 2;
head1->next->next->next->next = new node;
head1->next->next->next->next->data = 1;
head1->next->next->next->next->next = NULL;
if (isPalindrome(head1) == true)
{
cout << "head1 = Yes" << endl;
}
else
{
cout << "head1 = No" << endl;
}
head2 = new node;
head2->next = new node;
head2->next->next = new node;
head2->next->next->next = new node;
head2->data = 1;
head2->next->data = 2;
head2->next->next->data = 3;
head2->next->next->next->data = 2;
head2->next->next->next->next = NULL;
if (isPalindrome(head2) == true)
{
cout << "head2 = Yes" << endl;
}
else
{
cout << "head2 = No" << endl;
}
return 0;
}