用C语言练习5:实现一个双向链表拆分应用 // 将一个包含大小写字母的双向循环链表LO,拆分成只包含只包含大写字母的双向循环链表LC和只包含小写字母的双向循环链表LC
时间: 2024-09-16 20:06:05 浏览: 83
为了实现这个功能,首先你需要定义一个包含大小写字母的双向链表节点结构体,以及两个新的链表结构体,分别用于存储大写字母和小写字母。下面是简单的步骤和关键函数的实现:
```c
#include <stdio.h>
#include <ctype.h>
typedef struct Node {
char data;
struct Node* next;
struct Node* prev;
} Node;
typedef struct DoublyLinkedList {
Node* head;
Node* tail;
} DoublyLinkedList;
DoublyLinkedList* createList() {
DoublyLinkedList* list = (DoublyLinkedList*)malloc(sizeof(DoublyLinkedList));
list->head = list->tail = NULL;
return list;
}
Node* createNode(char c) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = c;
newNode->next = newNode->prev = newNode;
return newNode;
}
void append(DoublyLinkedList* list, char c) {
Node* newNode = createNode(c);
if (list->head == NULL) {
list->head = list->tail = newNode;
} else {
newNode->prev = list->tail;
list->tail->next = newNode;
list->tail = newNode;
}
}
void split(DoublyLinkedList* lo, DoublyLinkedList* lc, DoublyLinkedList* lcLower) {
Node* current = lo->head;
while (current != NULL) {
if (isupper(current->data)) {
append(lc, current->data);
} else if (islower(current->data)) {
append(lcLower, current->data);
}
current = current->next;
if (current == lo->head) break; // 循环链表,到达头部就回溯
}
}
void printList(DoublyLinkedList* list) {
Node* temp = list->head;
do {
printf("%c", temp->data);
temp = temp->next;
} while (temp != list->head);
printf("\n");
}
int main() {
DoublyLinkedList* lo = createList();
// ... 填充lo链表,比如 'Hello World'
DoublyLinkedList lc, lcLower;
split(lo, &lc, &lcLower);
printList(&lc);
printList(&lcLower);
return 0;
}
```
在这个代码中,`split` 函数遍历输入链表 `lo`,根据字符是否为大写字母将其添加到对应的链表 `lc` 或 `lcLower` 中。`main` 函数创建了输入链表,并打印出拆分后的结果。
阅读全文