单链表中每个结点存放一个字符。设计一个c语言算法,将该单链表按大小写字母、数字和其他字符拆成三个单循环链表(利用原来的结点)
时间: 2023-05-13 20:05:38 浏览: 111
将单链表中的信息分为字符、数字、其他三个循环链表.cpp
可以使用三个指针分别指向大小写字母、数字和其他字符的链表头,然后遍历原链表,根据结点存储的字符类型将其插入到对应的链表中。具体实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char data;
struct Node *next;
} Node;
void splitList(Node *head, Node **upper, Node **lower, Node **digit) {
Node *p = head, *pu = NULL, *pl = NULL, *pd = NULL;
while (p != NULL) {
if (p->data >= 'A' && p->data <= 'Z' || p->data >= 'a' && p->data <= 'z') {
if (pu == NULL) {
pu = p;
*upper = pu;
} else {
pu->next = p;
pu = p;
}
} else if (p->data >= '0' && p->data <= '9') {
if (pd == NULL) {
pd = p;
*digit = pd;
} else {
pd->next = p;
pd = p;
}
} else {
if (pl == NULL) {
pl = p;
*lower = pl;
} else {
pl->next = p;
pl = p;
}
}
p = p->next;
}
if (pu != NULL) pu->next = *upper;
if (pd != NULL) pd->next = *digit;
if (pl != NULL) pl->next = *lower;
}
int main() {
Node *head = (Node *) malloc(sizeof(Node));
head->data = 'a';
head->next = (Node *) malloc(sizeof(Node));
head->next->data = 'B';
head->next->next = (Node *) malloc(sizeof(Node));
head->next->next->data = '3';
head->next->next->next = (Node *) malloc(sizeof(Node));
head->next->next->next->data = '$';
head->next->next->next->next = NULL;
Node *upper = NULL, *lower = NULL, *digit = NULL;
splitList(head, &upper, &lower, &digit);
printf("Upper case letters: ");
Node *p = upper;
while (p != NULL) {
printf("%c ", p->data);
p = p->next;
if (p == upper) break;
}
printf("\n");
printf("Lower case letters: ");
p = lower;
while (p != NULL) {
printf("%c ", p->data);
p = p->next;
if (p == lower) break;
}
printf("\n");
printf("Digits: ");
p = digit;
while (p != NULL) {
printf("%c ", p->data);
p = p->next;
if (p == digit) break;
}
printf("\n");
return 0;
}
```
输出结果为:
```
Upper case letters: B
Lower case letters: a
Digits: 3
```
阅读全文