目录
解法一
1.判断是否为回文链表
#include <stack>
#include <iostream>
using namespace std;
typedef struct mylist
{
int value;
mylist *next;
};
bool is_palindromic_list(mylist *a_list)
{
if (a_list == nullptr)
{
return false;
}
stack<int> list_value;
mylist *fast, *slow;
while (fast->next != nullptr && fast->next->next != nullptr)
{
list_value.push(slow->next->value);
slow = slow->next;
fast = fast->next->next;
}
cout << "middle elem value is" << slow->next->value << endl;
if (fast->next != nullptr)
{
cout << "the list has odd num of node" << endl;
slow = slow->next;
}
int curvalue;
while (!list_value.empty())
{
curvalue = list_value.top();
cout << "stack top value is" << curvalue << endl;
cout << "list value is" << slow->next->value << endl;
if (curvalue != slow->next->value)
{
return false;
}
list_value.pop();
slow = slow->next;
}
return true;
}
2.创建链表
//创建链表
mylist* CreateList()
{
mylist* head=NULL;
//1.创建头结点
head =(mylist*) malloc(sizeof(mylist));
if (head == nullptr)
{
cout<<"分配内存失败"<<endl;
return head;
}
int len;
cout<<"输入节点个数:"<<endl;
cin>>len;
int val;
mylist *ptail=head;
for (int i=0;i<len;i++)
{
cin>>val;
mylist* pnode=(mylist*)malloc(sizeof(mylist));
if (pnode==nullptr)
{
cout<<"分配内存失败:"<<i<<endl;
return nullptr;
}
pnode->value=val;
pnode->next=nullptr;
ptail->next=pnode;
ptail = pnode;
}
return head;
}
3.打印链表
//打印链表
void printList(mylist *head)
{
if (head==nullptr)
{
return;
}
mylist *ptm=head->next;
while(ptm)
{
cout<<ptm->value<<" ";
ptm=ptm->next;
}
cout<<endl;
}
4.调用demo
int _tmain(int argc, _TCHAR* argv[])
{
mylist* head=CreateList();
printList(head);
bool res=Is_palindromic_list(head);
if (res)
{
cout<<"链表是回文链表"<<endl;
}
else
{
cout<<"不是回文链表"<<endl;
}
return 0;
}
参考阅读: