234. Palindrome Linked List
Difficulty: Easy
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false```
**Example 2:**
Input: 1->2->2->1
Output: true```
Follow up:
Could you do it in O(n) time and O(1) space?
Solution
思路1
简单的方法,时间复杂度和空间复杂度较高,遍历链表,将各个val
值存入vector
中,根据vector
的值判断是否是回文数。
Language: C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (head == NULL) return true;
ListNode* p = head;
vector<int> v;
while(p){
v.push_back(p->val);
p = p->next;
}
for (int i = 0; i < v.size()/2; i++){
if (v[i] == v[v.size() - 1 - i])
continue;
else
return false;
}
return true;
}
};
思路2
使用快慢指针;
- 快指针遍历完链表,慢指针刚好走到中间。
- 从慢指针的下一个节点开始反转。(链表长度奇数偶数都适用)
- 和原头指针开始做比较。
class Solution {
public:
ListNode* reverseList(ListNode* head){
ListNode* pre = NULL, *lnext = NULL;
while(head){
lnext = head->next;
head->next = pre;
pre = head;
head = lnext;
}
return pre;
}
bool isPalindrome(ListNode* head) {
if(head==NULL||head->next==NULL)
return true;
ListNode* slow=head;
ListNode* fast=head;
while (fast->next && fast->next->next){
fast = fast->next->next;
slow = slow->next;
}
slow = reverseList(slow->next);
while(slow!=NULL){
if(head->val!=slow->val)
return false;
head=head->next;
slow=slow->next;
}
return true;
}
};