判断字符串是否对称
算法思想:
- 从键盘中输入字符串,存放在数组中
- 将数组中元素依次摘下,尾插入法,插入到双链表中
- 分别定义指针从双链表头尾开始读取,比较对应的值
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
typedef int ElemType;
typedef struct DNode{
ElemType data;
struct DNode *prior;
struct DNode *next;
}DNode;
void CreateListR(DNode * &L,char a[],int n){ //尾插法建立双链表
DNode *s , *r;
int i;
//L为双链表的头结点
L = (DNode *)malloc(sizeof(DNode));//申请头结点
L->next = NULL;
r = L;
r->next = NULL;
//将字符串数组元素 尾查法依次插入到双链表中
for(i=0;i<n;i++){
s= (DNode *)malloc(sizeof(DNode));
s->data = a[i];
r->next = s;
s->prior=r;
r=s;
}
L->prior=s;
r->next=L;
}
int JudgeSym(DNode * &L){
DNode *p , *q;
//p为头节点的先驱
p=L->prior;
//q为头节点的后继
q=L->next;
while(p!=q){
if(p->data!=q->data)
return 0;
else{
p=p->prior;
q=q->next;
}
}
return 1;
}
void Destroy(DNode *&L){
DNode *pre = L, *p = L->next;
while(p!=L){
delete(pre);
pre=p;
p=p->next;
}
delete(pre);
}
int main(){
DNode *L;
int n=0;
char a[100];
printf("请输入字符串的长度\n");
scanf("%d",&n);
getchar();
printf("请输入字符串\n");
for(int i=0;i<n;i++)
//输入后立即从控制台取字符 无需换行
a[i] = getche();
printf("\n");
CreateListR(L,a,n);
if(JudgeSym(L)==1)
printf("双链表首尾对称\n");
else
printf("双链表首尾不对称\n");
Destroy(L);
return 0;
}