目录
题目来源:
链表的回文结构_牛客题霸_牛客网 (nowcoder.com)
题目描述:
实现代码:
struct ListNode* reverseList(struct ListNode* head){
if(!head) return NULL;
struct ListNode* n1,* n2,* n3;
n1=NULL;
n2=head;
n3 = n2->next;
while(n2)
{
n2->next =n1;
n1 = n2;
n2 = n3;
if(n3)
n3 = n3->next;
}
return n1;
}
class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
// write code here
ListNode* slow,*fast,*newhead1,*newhead2;
slow = fast = newhead1 = A;
while(fast && fast->next)
{
slow=slow->next;
fast=fast->next->next;
}
//逆置
newhead2 = reverseList(slow);
while(newhead1 && newhead2)
{
if(newhead1->val == newhead2->val)
{
newhead1=newhead1->next;
newhead2=newhead2->next;
}
else
{
return false;
}
}
return true;
}
};
思路分析:
思路:回文结构特征是正着读和反着读是一样的,因此我们只要找到链表的中间结点,再将链表的后半部分逆置,使用两个指针分别从头和中间结点开始遍历,如果在他们的next为空之前一直相等,说明该链表为回文结构。
过程:
1、我们使用快慢指针slow,fast找到链表的中间结点,分别使用newhead1和newhead2记录头结点和中间结点。
2、逆置中间结点后的链表。逆置链表若不会的话请参考此文章[ 链表OJ题 2 ] 反转链表_小白又菜的博客-CSDN博客
3、从newhead1和newhead2开始遍历,这里非常的巧妙,他们的长度一定是相等的,如上图举例,第二个元素2的next是指向3的,而后半部分逆置后其中的2元素也是指向3的,因此他们的长度是一样。就像一个相交链表一样。
4、判断结束的条件是newhead为空集合,如果相等就返回true,如果在遍历比较过程中只要有一个元素不相同,就返回false。
(本题完)