链接:https://leetcode.com/problems/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?
Hide Tags Linked List Two Pointers
Hide Similar Problems (E) Palindrome Number (E) Valid Palindrome (E) Reverse Linked List
检查一个链表是不是回文链表。我的思想是找到连标的中点,逆转链表的后一半,和前一半的链表做对比。还有可以用向量或者栈来做,不过这样浪费了空间。递归做法还不会。
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
ListNode *t=new ListNode(0),*cur=NULL;
t->next=head;
cur=head;
head=head->next;
cur->next=NULL;
while(head)
{
t->next=head;
head=head->next;
t->next->next=cur;
cur=t->next;
}
cur=t->next;
delete t;
return cur;
};
bool isPalindrome(ListNode* head) {
if(head==NULL) return true;
ListNode*p1=head,*p2=head;
while(p1&&p1->next!=NULL)
{
p1=p1->next->next;
p2=p2->next;
}
p2=reverseList(p2);
p1=head;
while(p2)
{
if(p2->val!=p1->val)
return false;
p1=p1->next;
p2=p2->next;
}
return true;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/efergrehbtrj/article/details/46879741