题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
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) {
if(head == nullptr || head->next == nullptr){
return true;
}
ListNode *pre = nullptr;
ListNode *slow = head;
ListNode *fast = head;
while(fast && fast->next){
fast = fast->next->next;
ListNode *temp = slow->next;
slow->next = pre;
pre = slow;
slow = temp;
}
//节点个数为奇数
if(fast){
return isequal(pre, slow->next);
}else{
return isequal(pre, slow);
}
}
bool isequal(ListNode* head, ListNode *mid){
while(head && mid){
if(head->val != mid->val){
return false;
}
head = head->next;
mid = mid->next;
}
return true;
}
};
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
print('Hello world!')

