判断链表结点对称 (10 分)
设计算法,判断带头结点的循环双向链表中的数据结点是否对称。 如果对称,输出“yes” 如果不对称,输出“no” 链表空则输出“NULL”
#include <stdio.h>
#include <iostream>
using namespace std;
typedef char ElemType;
typedef struct DNode //定义循环双链表结点类型
{
ElemType data;
struct DNode *prior,*next;
} DLinkNode;
void InitList(DLinkNode *&L){//创建空链表
L = new DNode;
L->next=L->prior=L;
}
void DestroyList(DLinkNode *&L){//销毁链表
DLinkNode *pre = L , *p = L->next;
while(p!=L){
delete(pre);
pre= p ;
p = p->next;
}
delete(pre);
}
bool ListInsert(DLinkNode *&L,int i,ElemType e){//插入值
int j=0;
DLinkNode *p = L,*s;
while(j<i-1&&p){
p = p->next;
j++;
}
if(!p){
return false;
}
s = new DLinkNode;
s->data = e;
s->next = p->next;
s->prior = p;
(p->next)->prior = s;
p->next = s;
}
//要求写出以下函数实现
void DispList(DLinkNode *L);
int Symm(DLinkNode *L);
int main()
{
DLinkNode *h;
ElemType e;
InitList(h);
int i=1;
char ch;
while((ch=getchar())!='\n')
{
ListInsert(h,i,ch);
i++;
}
DispList(h);
if(Symm(h)==1)
printf("yes\n");
else if (Symm(h)==0)printf("no\n");
else printf("NULL\n");
DestroyList(h);
return 0;
}
//#include <iostream>
//using namespace std;
void DispList(DLinkNode *L){//打印链表
DLinkNode *p = new DLinkNode;
p = L->next;
if(!L) printf("NULL");
while(p!=L&&p){
printf("%c ",p->data);
p = p->next;
}
printf("\n");
}
int Symm(DLinkNode *L){//判断是否对称
if(L->next==L) return -1;//循环双链表判断是否为空
DLinkNode *r=L->next;
DLinkNode *l=L->prior;
while(l!=r){
if(l->data==r->data){
r=r->next;
l=l->prior;
}
else return 0;
}
return 1;
}