问题:
234. Palindrome Linked List(从前往后读和从后往前读是一样的)
参考链接:
1、【LeetCode】234. Palindrome Linked List (2 solutions)
2、http://www.cnblogs.com/HorribleMe/p/4878833.html
第一种解法:
(符合题目要求:时间复杂度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:
bool isPalindrome(ListNode *head) {
if (!head||!head->next)
return true;
ListNode *mid=getmid(head);//中间节点
ListNode *head2=rever(mid);//中间节点作为头指针的链表反转
while(head&&head2)
{
if(head->val!=head2->val)
return false;
else
head=head->next;
head2=head2->next;
}
return true;
}
private:
ListNode* getmid(ListNode *head)
{
ListNode *slow=head;
ListNode *fast=head;
if (!head||!head->next)
return head;
while(fast)
{
slow=slow->next;
fast=fast->next;
if (fast)
fast=fast->next;
}
return slow;
}
private:
ListNode* rever(ListNode *head)
{
ListNode *prev = NULL, *cur = head, *tmp;
while(cur)
{
tmp=cur->next;
cur->next=prev;
prev=cur;
cur=tmp;
}
return prev;
}
};