回文链表
编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
方法1:
迭代链表,使用栈依次存放,然后再一次迭代比较用栈依次比较一半的回文链表
时间复杂度O(n),空间O(1)
bool isPalindrome(ListNode* head) {
stack<ListNode *> s;
if(head==NULL) return true;
ListNode* p=head;
while(p)
{
s.push(p);
p=p->next;
}
p=head;
int len=s.size()/2;
for(int i=0;i<len+1;i++)
{
ListNode *temp=s.top();
if(temp->val!=p->val)
return false;
s.pop();
p=p->next;
}
return true;
}
方法2:
快慢指针+反转链表
时间复杂度O(n),空间O(1)