题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
http://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
bool isPail(struct ListNode* head ) {
// write code here
struct ListNode* p1 = head;//快指针
struct ListNode* p2 = head;//慢指针
struct ListNode* n = NULL;
if(NULL == head || NULL == head->next) return true;
while(NULL!=p1 && NULL!=p1->next)
{
p1 = p1->next->next;
p2 = p2->next;
}
p1 = p2->next;
p2->next = NULL;
while(NULL != p1)
{
n = p1->next;
p1->next = p2;
p2 = p1;
p1 = n;
}
p1 = head;
while(NULL!=p1 && NULL!=p2)
{
if(p1->val != p2->val) return false;
p1 = p1->next;
p2 = p2->next;
}
return true;
}