使用C语言,已知由一个线性链表表示的线性表中含有三类字符的数据元素(如:字母字 符、数字字符和其他字符),试编写算法将该线性链表分割为三个循环链表,其中每个循环 链表表示的线性表中均只含一类字符。
时间: 2023-05-30 07:05:39 浏览: 89
思路:
- 遍历原链表,将不同类型的节点分别插入对应类型的循环链表中
- 最后将三个循环链表合并成一个线性链表
代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 链表节点
typedef struct ListNode {
char data;
struct ListNode *next;
} ListNode;
// 循环链表
typedef struct {
ListNode *head;
ListNode *tail;
} CircularList;
// 初始化循环链表
void initCircularList(CircularList *list) {
list->head = NULL;
list->tail = NULL;
}
// 插入节点到循环链表尾部
void insertNode(CircularList *list, char data) {
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->data = data;
node->next = NULL;
if (list->head == NULL) {
list->head = node;
list->tail = node;
node->next = list->head;
} else {
list->tail->next = node;
list->tail = node;
node->next = list->head;
}
}
// 合并三个循环链表为一个线性链表
ListNode *mergeLists(CircularList *list1, CircularList *list2, CircularList *list3) {
ListNode *head = NULL, *tail = NULL;
// 拼接第一个循环链表
if (list1->head != NULL) {
head = list1->head;
tail = list1->tail;
tail->next = NULL;
}
// 拼接第二个循环链表
if (list2->head != NULL) {
if (tail == NULL) {
head = list2->head;
tail = list2->tail;
} else {
tail->next = list2->head;
tail = list2->tail;
}
tail->next = NULL;
}
// 拼接第三个循环链表
if (list3->head != NULL) {
if (tail == NULL) {
head = list3->head;
tail = list3->tail;
} else {
tail->next = list3->head;
tail = list3->tail;
}
tail->next = NULL;
}
return head;
}
// 分割链表为三个循环链表
void splitList(ListNode *head, CircularList *list1, CircularList *list2, CircularList *list3) {
ListNode *node = head;
while (node != NULL) {
char data = node->data;
ListNode *nextNode = node->next;
if (data >= 'a' && data <= 'z' || data >= 'A' && data <= 'Z') {
// 字母字符
insertNode(list1, data);
} else if (data >= '0' && data <= '9') {
// 数字字符
insertNode(list2, data);
} else {
// 其他字符
insertNode(list3, data);
}
node = nextNode;
}
}
// 打印链表
void printList(ListNode *head) {
ListNode *node = head;
while (node != NULL) {
printf("%c ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
// 构造线性链表
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
head->data = 'a';
head->next = (ListNode *)malloc(sizeof(ListNode));
head->next->data = '1';
head->next->next = (ListNode *)malloc(sizeof(ListNode));
head->next->next->data = '*';
head->next->next->next = (ListNode *)malloc(sizeof(ListNode));
head->next->next->next->data = 'B';
head->next->next->next->next = (ListNode *)malloc(sizeof(ListNode));
head->next->next->next->next->data = 'c';
head->next->next->next->next->next = NULL;
// 分割链表为三个循环链表
CircularList list1, list2, list3;
initCircularList(&list1);
initCircularList(&list2);
initCircularList(&list3);
splitList(head, &list1, &list2, &list3);
// 合并三个循环链表为一个线性链表
ListNode *newHead = mergeLists(&list1, &list2, &list3);
// 打印新链表
printList(newHead);
return 0;
}
```
输出结果:
```
a B c 1 *
```
阅读全文