lintcode-223-回文链表
223-回文链表
设计一种方式检查一个链表是否为回文链表。
样例
1->2->1 就是一个回文链表。
挑战
O(n)的时间和O(1)的额外空间。
标签
链表
思路
找到链表中点后,翻转链表后半部分,然后从头开始比较两个子链表。翻转链表代码源于 LintCode-35.翻转链表
code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*
* @param head: A ListNode.
* @return: A boolean.
*/
bool isPalindrome(ListNode * head) {
// write your code here
if (head == NULL || head->next == NULL) {
return true;
}
ListNode *fast = head, *slow = head;
while (fast->next != NULL && fast->next->next != NULL) {
fast = fast->next->next;
slow = slow->next;
}
ListNode *last = slow->next;
slow->next = NULL;
last = reverse(last);
while (last != NULL) {
if (head->val != last->val) {
return false;
}
head = head->next;
last = last->next;
}
if (head == NULL || head->next == NULL) {
return true;
}
return false;
}
ListNode *reverse(ListNode *head) {
// write your code here
ListNode *l1 = NULL, *l2 = NULL, *l3 = NULL;
l1 = head;
// 链表没有节点或有一个节点
if (l1 == NULL || l1->next == NULL) {
return l1;
}
l2 = l1->next;
// 链表有2节点
if (l2->next == NULL) {
l2->next = l1;
l1->next = NULL;
return l2;
}
l3 = l2->next;
// 链表有3个以上节点
if (l2->next != NULL) {
while (l2 != l3) {
l2->next = l1;
if (l1 == head)
l1->next = NULL;
l1 = l2;
l2 = l3;
if (l3->next != NULL)
l3 = l3->next;
}
l2->next = l1;
return l2;
}
}
};