Description:
题目大意:判断一个链表是不是回文结构
解题思路:
算法标签:链表,快慢指针,反转链表
- 利用快慢指针寻找中点
- 反转中点以后的链表
- 依次对比
代码:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
ListNode* reverselist(ListNode* head) {
ListNode* pre = NULL;
while(head != NULL) {
// 存储下一个节点
ListNode* next = head -> next;
head -> next = pre;
pre = head;
head = next;
}
return pre;
}
bool isPail(ListNode* head) {
if(head -> next == NULL)
return true;
ListNode* fast = head;
ListNode* slow = head;
// 通过快慢指针找到中点
while(fast != NULL && fast -> next != NULL) {
fast = fast -> next -> next;
slow = slow -> next;
}
// 如果 fast 不为空,说明链表有奇数个节点
if(fast != NULL)
fast = fast -> next;
// 反转后半部分的节点
slow = reverselist(slow);
fast = head;
while(slow != NULL) {
if(fast -> val != slow -> val)
return false;
fast = fast -> next;
slow = slow -> next;
}
return true;
}
};