1. 题目
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
2. 方法一:用堆栈
2.1. 代码
设定slow和fast两个指针,fast比slow快两倍,在一边移动slow的时候,一边将slow->val压入堆栈中以比较。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==NULL||head->next==NULL) return true;
ListNode *fast=head->next,*slow=head;
stack<int> slow_stack;
while(fast->next!=NULL&&fast->next->next!=NULL)
{
fast=fast->next->next;
slow_stack.push(slow->val);
slow=slow->next;
}
slow_stack.push(slow->val);
slow=slow->next;
if(fast->next!=NULL)
{
slow=slow->next;
}
while(slow!=NULL&&slow->val==slow_stack.top())
{
slow_stack.pop();
slow=slow->next;
}
if(slow==NULL)
return true;
else
return false;
2.2. 结果
3. 方法二
3.1. 代码
设定slow和fast两个指针,fast比slow快两倍,在一边移动slow的时候,一边将slow指向的链表反转。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==NULL||head->next==NULL) return true;
ListNode *fast=head->next,*slow=head,*slow_next=slow->next,*temp;
slow->next=NULL;
while(fast->next!=NULL&&fast->next->next!=NULL)
{
fast=fast->next->next;
temp=slow_next->next;
slow_next->next=slow;
slow=slow_next;
slow_next=temp;
}
if(fast->next!=NULL)
{
slow_next=slow_next->next;
}
while(slow!=NULL&&slow->val==slow_next->val)
{
slow_next=slow_next->next;
slow=slow->next;
}
if(slow==NULL)
return true;
else
return false;
}
};