题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
http://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
快慢指针找到中间节点,以中间节点为界将后半部分翻转,将翻转后的那一半链表与前一半链表做回文比较。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
bool isPail(ListNode* head) {
// write code here
if(head == nullptr || head->next == nullptr) return true;
ListNode *fast = head, *mid = head;
while (fast && fast->next) { // 找到中间节点
fast = fast->next->next;
mid = mid->next;
}
fast = mid->next;
mid->next = nullptr;
ListNode *end = nullptr;
// 进行后半部分翻转
while(fast) {
end = fast->next;
fast->next = mid;
mid = fast;
fast = end;
}
//判断回文
end = mid;
while (head && end) {
if (head->val != end->val) {
return false;
}
head = head->next;
end = end->next;
}
return true;
}
};
查看12道真题和解析