1. 题目描述
描述
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
测试样例:
1->2->2->1
返回:true
2. 思路
1、用快慢指针,找到中间节点(返回链表的中间结点)
2、从中间节点开始,对后半段逆置(反转链表)
3、对前半段和后半段进行比较
3. 代码实现
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
struct ListNode* reverseList(struct ListNode* head) {
if (head == NULL) {
return NULL;
}
struct ListNode* cur, *newhead;
cur = head;
newhead = NULL;
while (cur) {
struct ListNode* next = cur->next;
// 头插
cur->next = newhead;
newhead = cur;
cur = next;
}
return newhead;
}
struct ListNode* middleNode(struct ListNode* head) {
struct ListNode* slow, *fast;
slow = fast = head;
while (fast &&
fast ->next) { //停止的条件是fast ==NULL 或者fast->next ==NULL, 继续的条件,就是这俩条件与
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
struct ListNode* midNode = middleNode(A);
struct ListNode* rehead = reverseList(midNode);
while(A,rehead)
{
if(A->val != rehead->val)
{
return false;
}
A=A->next;
rehead =rehead->next;
}
return true;
}
};