判断链表是否是回文链表主要通过判断对应位置的元素值是否是相等的
第一种解法:将原有链表反转获取新的链表,与原有的链表比较,判断对应元素的值是否相等
#include <iostream>
using namespace std ;
struct node
{
int data ;
struct node *next ;
};
typedef struct node *PLIST;
typedef struct node NODE;
PLIST createList_link()
{
PLIST head=new struct node;
head->next=NULL;
return head ;
}
void insertTail(PLIST llist,int x)
{
PLIST tail=llist->next;
PLIST temp=new struct node;
temp->data=x;
temp->next=NULL;
if(tail==NULL)
{
llist->next=temp;
return;
}
else
{
while(tail->next!=NULL)
{
tail=tail->next;
}
}
tail->next=temp;
}
void insertHead(PLIST llist,int x)
{
PLIST tail=llist->next;
PLIST temp=new struct node;
temp->data=x;
temp->next=tail;
llist->next=temp;
}
void printList_link(PLIST head)
{
for(PLIST p=head->next;p!=NULL;p=p->next){
cout<<p->data<<" ";
}
cout<<endl;
}
PLIST reverseList_link(PLIST head)
{
PLIST p=head->next;
PLIST copy=createList_link();
while(p!=NULL)
{
insertHead(copy,p->data);
p=p->next;
}
return copy;
}
int main()
{
//begin 生成链表
int flag=1,arr[]={3,324,34,34,324,3};
PLIST head=createList_link();
for(int i=0;i<6;i++)
{
insertHead(head,arr[i]);
}
PLIST copy=reverseList_link(head);
for(PLIST p=head->next,q=copy->next;p!=NULL;p=p->next,q=q->next)
{
if(p->data!=q->data)
{
flag=0;
break;
}
}
if(flag)
cout<<"Yes";
else
cout<<"No";
//end
return 0;
}
第二种解法:借助栈结构和双指针,一个指针的位移为1并将此时访问的元素放到栈中,另一个指针的位移为2,当位移为2的指针到达末尾时,位移为1的指针到达链表中间位置。此后将栈中元素与链表中元素值比对
#include <iostream>
#include<stack>
using namespace std ;
struct node
{
int data ;
struct node *next ;
};
typedef struct node *PLIST;
typedef struct node NODE;
PLIST createList_link()
{
PLIST head=new struct node;
head->next=NULL;
return head ;
}
void insertTail(PLIST llist,int x)
{
PLIST tail=llist->next;
PLIST temp=new struct node;
temp->data=x;
temp->next=NULL;
if(tail==NULL)
{
llist->next=temp;
return;
}
else
{
while(tail->next!=NULL)
{
tail=tail->next;
}
}
tail->next=temp;
}
void printList_link(PLIST head)
{
for(PLIST p=head->next;p!=NULL;p=p->next){
cout<<p->data<<" ";
}
cout<<endl;
}
int main()
{
//begin 生成链表
int flag=1,arr[]={3,324,34,5,34,324,3};
PLIST head=createList_link();
for(int i=0;i<7;i++)
{
insertTail(head,arr[i]);
}
//end
stack<int> s;
PLIST n1=head->next,n2=head->next->next;
while(n2!=NULL&&n2->next!=NULL)
{
s.push(n1->data);
n1=n1->next;
n2=n2->next->next;
}
if(n2!=NULL&&n2->next==NULL)
{
s.push(n1->data);
n1=n1->next;
}
else if(n2==NULL)
{
n1=n1->next;
}
while(n1!=NULL)
{
if(n1->data!=s.top())
{
flag=0;
break;
}
s.pop();
n1=n1->next;
}
if(flag)
cout<<"Yes";
else
cout<<"No";
return 0;
}
显然,第一种做法需要需要新的链表,第二种方法借助栈结构,但是使用双指针是在太鸡肋,虽然思路挺好,但是实现太比较麻烦,如果想使用栈结构,可以先将链表全部元素都压入栈中,再重新遍历比较。