1. 使用2个指针,快慢指针各一个,每次快指针移动一个,慢指针移动2个。
2. 当快指针不为NULL时候,将慢指针push到栈中。
3. 当快指针等于NULL时候,说明链表前半部分已经被压入栈中。
4. 每次栈Top元素与当前慢指针元素比较,如果不相等则返回false。如果相等,则栈Pop,慢指针++。
5. 链表奇数或者偶数节点需要判断。
#include <iostream>
#include <stack>
struct node
{
int data;
node* next;
node(int eData, node* eNext)
{
data = eData;
next = eNext;
}
};
bool isPanli(node* head)
{
std::stack<node*> stk;
node* slow = head;
node* fast = head;
bool flag = false;
while (fast)
{
stk.push(slow);
slow = slow->next;
fast = fast->next;
if (fast)
{
fast = fast->next;
}
else
flag = true;
}
if (flag)
stk.pop();
while (!stk.empty())
{
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;
}