Check whether a singly linked list is a pallindrome.
Eg: 1->2->1 Ans: True
Eg: 1->2->1 Ans: True
1->3->2->1 Ans: False
1.设置两个指针fast和slow,fast和slow指针一次移动两个和一个单位,同时将slow指针所指的元素入栈。
2.当fast指针指到空时,slow指针指向了中间点。
3.然后将slow指针所指的元素和栈顶元素比较,如果相等,slow指针继续移动,pop栈中的元素,继续比较指导不等,或栈为空。
用flag标志位为false表示元素总数为偶数个。如果为奇数个元素时,栈必须弹出中间的元素。
#include <iostream>
#include <stack>
struct node{
int data;
node* next;
node(int eData,node* eNext){
data = eData;
next = eNext;
}
};
bool isPanli(node*head){
bool flag = false;//represent even
std::stack<node*> stk;
node* slow = head;
node* fast = head;
while (fast)
{
stk.push(slow);
slow = slow->next;
fast = fast->next;
if (fast)
{
fast = fast->next;
}
else
flag = true;//represent odd 奇数个元素
}
if (flag)//odd count elem , pop the middle elem
{
stk.pop();
}
while (stk.size())
{
if (stk.top()->data == slow->data)
{
stk.pop();
slow = slow->next;
}
else
return false;
}
return true;
}
int main()
{
node* n5 = new node(1, NULL);
node* n4 = new node(2, n5);
node* n3 = new node(3, n4);
//node* n2 = new node(3, n3);
node* n1 = new node(2, n3);
node* n0 = new node(1, n1);
bool res = isPanli(n0);
return 0;
}
本文介绍了一种使用栈辅助的双指针方法来检查单链表是否为回文结构。通过快慢指针找到中点,并利用栈保存前半部分元素进行对比,实现了高效的回文判断。
386

被折叠的 条评论
为什么被折叠?



