本题代码如下
int symmetry(linklist* L)//判断循环双链表是否对称
{
lnode* p = (*L)->next, * q = (*L)->prior;
while (p != q && q->next != p)
{
if (p->data != q->data)
return 0;
else
{
p = p->next;
q = q->prior;
}
}
return 1;
}
完整测试代码
#include<stdio.h>
#include<stdlib.h>
typedef struct lnode
{
char data;
struct lnode* prior;
struct lnode* next;
}lnode, * linklist;
int n = 4;
char a[4] = { 'A','B','A','B' };
void buildlinklist(linklist* L)//建立循环双链表
{
(*L)->next = *L;//初始化头结点
(*L)->prior = *L;
lnode* r = *L;
int i = 0;
for (i = 0; i < n; i++)
{
lnode* s = (lnode*)malloc(sizeof(lnode));//创建新结点
s->data = a[i];
s->next = r->next;//插入新结点
s->prior = r;
r->next->prior = s;
r->next = s;
r = s;
}
}
int symmetry(linklist* L)//判断循环双链表是否对称
{
lnode* p = (*L)->next, * q = (*L)->prior;
while (p != q && q->next != p)
{
if (p->data != q->data)
return 0;
else
{
p = p->next;
q = q->prior;
}
}
return 1;
}
void print(linklist* L)//输出链表
{
lnode* k = (*L)->next;
while (k != *L)
{
printf("%c ", k->data);
k = k->next;
}
}
int main()
{
linklist L = (lnode*)malloc(sizeof(lnode));//创建头结点
L->next = L;
L->prior = L;
buildlinklist(&L);//构建循环双链表
printf("原始单链表为:");
print(&L);
int ret = symmetry(&L);
if (ret == 1)
{
printf("\n带头结点的循环双链表对称");
}
else
{
printf("\n带头结点的循环双链表不对称");
}
return 0;
}
用char a[4] = { 'A','B','B','A' }测试
用char a[4] = { 'A','B','A','B' }测试