设单链表中存放着n个字符,设计算法,判断该字符串中是否有中心对称关系
设单链表中存放着n个字符,设计算法,判断该字符串中是否有中心对称关系
程序代码:
#include <stdio.h>
#include <stdlib.h>
#define SIZE (sizeof(ND))
typedef struct node {
char ch;
struct node *next;
} ND, *PN;
void createList(PN head) {
PN cur = head, pnew = NULL;
char c = getchar();
if(c == '\n') {
free(head);
exit(EXIT_FAILURE);
} else head->ch = c;
while((c = getchar()) != '\n') {
pnew = malloc(SIZE);
if(pnew == NULL) exit(EXIT_FAILURE);
pnew->ch = c;
cur->next = pnew;
cur = cur->next;
}
cur->next = NULL;
}
void freeList(PN head) {
PN p;
while(head != NULL) {
p = head->next;
free(head);
head = p;
}
}
int main(void) {
PN cur = NULL, pnew = NULL, rhead = NULL, rcur = NULL;
PN head = malloc(SIZE);
if(head) createList(head);
else exit(EXIT_FAILURE);
for(cur = head; cur; cur = cur->next) {
pnew = malloc(SIZE);
if(pnew == NULL) exit(EXIT_FAILURE);
pnew->ch = cur->ch;
pnew->next = rhead;
rhead = pnew;
}
for(cur = head, rcur = rhead; cur; cur = cur->next, rcur = rcur->next) {
if(cur->ch != rcur->ch) {
puts("No!");
break;
}
}
if(!cur) puts("Yes!");
freeList(head);
freeList(rhead);
return 0;
}
