用c语言编写程序使单链表中每个结点存放一个字符。设计一个算法,将该单链表按字母、数字和其他字符拆成三个单循环链表(利用原来的结点)
时间: 2023-05-13 12:05:30 浏览: 96
可以使用以下代码实现:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char data;
struct Node *next;
} Node;
void splitList(Node *head, Node **alpha, Node **num, Node **other) {
Node *cur = head;
while (cur != NULL) {
Node *next = cur->next;
if (cur->data >= 'a' && cur->data <= 'z') {
cur->next = *alpha;
*alpha = cur;
} else if (cur->data >= '0' && cur->data <= '9') {
cur->next = *num;
*num = cur;
} else {
cur->next = *other;
*other = cur;
}
cur = next;
}
}
int main() {
Node *head = NULL;
Node *alpha = NULL;
Node *num = NULL;
Node *other = NULL;
// 构造单链表
head = (Node *)malloc(sizeof(Node));
head->data = 'a';
head->next = (Node *)malloc(sizeof(Node));
head->next->data = '1';
head->next->next = (Node *)malloc(sizeof(Node));
head->next->next->data = 'B';
head->next->next->next = (Node *)malloc(sizeof(Node));
head->next->next->next->data = '2';
head->next->next->next->next = (Node *)malloc(sizeof(Node));
head->next->next->next->next->data = '*';
head->next->next->next->next->next = NULL;
// 拆分单链表
splitList(head, &alpha, &num, &other);
// 输出结果
printf("字母链表:");
Node *cur = alpha;
while (cur != NULL) {
printf("%c ", cur->data);
cur = cur->next;
}
printf("\n数字链表:");
cur = num;
while (cur != NULL) {
printf("%c ", cur->data);
cur = cur->next;
}
printf("\n其他字符链表:");
cur = other;
while (cur != NULL) {
printf("%c ", cur->data);
cur = cur->next;
}
printf("\n");
return 0;
}
阅读全文