Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
判断链表是否为回文。
可以反转链表,再判断,请阅 反 转 单 链 表
空间复杂度O(n)。
/**
* 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) {
int a[100000],n=0;
while (head) {
a[n++] = head->val;
head = head->next;
}
for (int i=0;i<n/2;i++){
if (a[i]!=a[n-i-1]) return false;
}
return true ;
}
};
下面的方法,空间复杂度为O(1)
例如1,2,3,4,3,2,1 后半部分反转后 1,2,3,4,1,2,3
若是回文,则前后部分链表一致
/**
* 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||!head->next) return true;
ListNode *p,*q,*t,*x;
p = q = head;
// 找到中间的节点 p
while (q->next&&q->next->next) {
p = p->next;
q = q->next->next;
}
// 反转p后面的链表
q = p->next;
x = q->next;
q->next = NULL;
while (x) {
t = x->next;
x->next = q;
q = x;
x = t;
}
p->next = q;
// 判断前一段链表 是否和后一段相同
while (q) {
if (head->val != q->val) return false;
head = head->next;
q = q->next;
}
return true;
}
};
/**
* 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||!head->next) return true;
ListNode *p,*q,*t,*x;
p = q = head;
// 找到中间的节点 p
while (q->next&&q->next->next) {
p = p->next;
q = q->next->next;
}
// 反转p后面的链表
q = p->next;
x = q->next;
q->next = NULL;
while (x) {
t = x->next;
x->next = q;
q = x;
x = t;
}
p->next = q;
// 判断前一段链表 是否和后一段相同
while (q) {
if (head->val != q->val) return false;
head = head->next;
q = q->next;
}
return true;
}
};