https://leetcode-cn.com/problems/palindrome-linked-list/description/
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* Reverse(ListNode* head){
ListNode* prev = NULL;
ListNode* next;
while(head){
next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
bool isPalindrome(ListNode* head) {
ListNode* Head = new ListNode(-1);
Head->next = head;
ListNode* cur1 = Head;
ListNode* cur2 = Head;
while(cur2 && cur2->next){
cur1 = cur1->next;
cur2 = cur2->next->next;
}
cur2 = cur1->next;
cur2 = Reverse(cur2);
while(cur2){
if(head->val == cur2->val){
head = head->next;
cur2 = cur2->next;
}
else{
return false;
}
}
return true;
}
};