-
题目描述
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
测试样例:
1->2->2->1
返回:true
-
思路分析:
先遍历一遍链表,计算出节点的个数,再从头开始走,走到链表的中间位置,然后把链表的中间位置作为要逆置的头结点,最后再把逆置后的节点与头结点到中间位置之前的节点进行比较,如果相等,则就是回文结构,否则就不是回文结构。
- 具体代码如下:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
ListNode* reverseList(ListNode* phead)
{
struct ListNode* newhead=NULL;
struct ListNode* cur=phead;
while(cur)
{
struct ListNode* next=cur->next;
cur->next=newhead;
newhead=cur;
cur=next;
}
return newhead;
}
bool chkPalindrome(ListNode* A) {
int n=0;
struct ListNode* cur=A;
while(cur)//判断链表的个数
{
cur=cur->next;
n++;
}
cur=A;
int mid=n/2;
while(mid--)//链表从头开始走到中间位置
{
cur=cur->next;
}
struct ListNode* head1=A;
struct ListNode* head2=reverseList(cur);
mid=n/2;
while(mid--)
{
if(head1->val==head2->val)
{
if(head1&&head2)
head1=head1->next;
head2=head2->next;
}
else
{
return false;
}
}
return true;
}
};
其实这道题有一个漏洞,它题目要求链表长度小于等于900,那如果用数组来判断的话,也是可以的,甚至比使用链表更简单
- 具体实现代码如下:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
int a[900];
int n=0;
struct ListNode* cur=A;
while(cur)
{
a[n]=cur->val;
cur=cur->next;
n++;
}
int left=0;
int right=n-1;
while(left<right)
{
if(a[left]!=a[right])
{
return false;
}
left++;
right--;
}
return true;
}
};