用c++写一个1:假设有一个带有头节点的单链接列表L,每个节点值由单个数字、小写字母和大写字母组成。设计一个算法,将其拆分为三个带有头部节点的单链接列表L1、L2和L3。L1包含L中的所有数字节点,L2包含L中的所有小写字母节点,L3包含L字母节点中的所有大写节点
时间: 2023-04-05 11:02:53 浏览: 95
可以使用以下代码实现:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char data;
struct Node *next;
} Node;
void splitList(Node *L, Node **L1, Node **L2, Node **L3) {
Node *p = L->next;
Node *p1 = *L1 = (Node *)malloc(sizeof(Node));
Node *p2 = *L2 = (Node *)malloc(sizeof(Node));
Node *p3 = *L3 = (Node *)malloc(sizeof(Node));
while (p) {
if (p->data >= '0' && p->data <= '9') {
p1->next = p;
p1 = p1->next;
} else if (p->data >= 'a' && p->data <= 'z') {
p2->next = p;
p2 = p2->next;
} else if (p->data >= 'A' && p->data <= 'Z') {
p3->next = p;
p3 = p3->next;
}
p = p->next;
}
p1->next = NULL;
p2->next = NULL;
p3->next = NULL;
}
int main() {
Node *L = (Node *)malloc(sizeof(Node));
L->next = NULL;
Node *p = L;
char str[] = "aBc1De2Fg3HiJkLmN";
for (int i = 0; str[i]; i++) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = str[i];
node->next = NULL;
p->next = node;
p = p->next;
}
Node *L1, *L2, *L3;
splitList(L, &L1, &L2, &L3);
printf("L1: ");
p = L1->next;
while (p) {
printf("%c ", p->data);
p = p->next;
}
printf("\nL2: ");
p = L2->next;
while (p) {
printf("%c ", p->data);
p = p->next;
}
printf("\nL3: ");
p = L3->next;
while (p) {
printf("%c ", p->data);
p = p->next;
}
printf("\n");
return 0;
}
输出结果为:
L1: 1 2 3
L2: a c e g i k m
L3: B D F H J L N
阅读全文