(线性表)设单链表的表头指针为h,结点结构由data和next两个域构成,其中data域为字符型。写出算法dc(h,n),判断该链表的前n个字符是否中心对称 输入 xyx xyyx 输出 输出结果:Yes 使用C语言写出完整代码
时间: 2024-05-05 13:17:23 浏览: 114
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct Node {
char data;
struct Node *next;
} Node, *LinkedList;
LinkedList createLinkedList(char *str) {
int len = strlen(str);
LinkedList head = (LinkedList) malloc(sizeof(Node));
head->next = NULL;
Node *p = head;
for (int i = 0; i < len; i++) {
Node *node = (Node *) malloc(sizeof(Node));
node->data = str[i];
node->next = NULL;
p->next = node;
p = node;
}
return head;
}
void printLinkedList(LinkedList head) {
Node *p = head->next;
while (p != NULL) {
printf("%c", p->data);
p = p->next;
}
printf("\n");
}
char getAt(LinkedList head, int index) {
Node *p = head->next;
for (int i = 0; i < index; i++) {
p = p->next;
}
return p->data;
}
int dc(LinkedList head, int n) {
if (n <= 1) {
return 1;
}
char arr[MAX_SIZE];
int i;
for (i = 0; i < n / 2; i++) {
arr[i] = getAt(head, i);
}
if (n % 2 == 1) {
i++;
}
for (; i < n; i++) {
if (getAt(head, i) != arr[n - i - 1]) {
return 0;
}
}
return 1;
}
int main() {
LinkedList list = createLinkedList("xyyxx");
printLinkedList(list);
if (dc(list, 5)) {
printf("Yes\n");
} else {
printf("No\n");
}
return 0;
}
```
阅读全文