C语言实现简单可变长度字符串容器 - 使用链表
以下是一个简单的实现,使用链表来存储字符串:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char* str;
struct node* next;
} Node;
typedef struct {
Node* head;
Node* tail;
} Container;
void init(Container* container) {
container->head = NULL;
container->tail = NULL;
}
void add(Container* container, char* str) {
Node* node = (Node*)malloc(sizeof(Node));
node->str = (char*)malloc(strlen(str) + 1); // Allocate memory for string
strcpy(node->str, str);
node->next = NULL;
if (container->head == NULL) {
container->head = node;
container->tail = node;
} else {
container->tail->next = node;
container->tail = node;
}
}
void print(Container* container) {
Node* node = container->head;
while (node != NULL) {
printf('%s\n', node->str);
node = node->next;
}
}
int main() {
Container container;
init(&container);
add(&container, 'Hello');
add(&container, 'World');
add(&container, '!');
print(&container);
return 0;
}
该程序定义了两个结构体,Node和Container。Node代表一个节点,包含一个字符串指针和一个指向下一个节点的指针。Container代表一个容器,包含一个指向头节点的指针和一个指向尾节点的指针。init函数用于初始化容器,将头节点和尾节点都设置为NULL。add函数用于向容器中添加一个字符串,首先分配内存以存储该字符串,然后将字符串复制到新分配的内存中。如果容器为空,将新节点设置为头节点和尾节点。否则,将新节点添加到链表的末尾。print函数用于打印容器中的所有字符串。
在main函数中,创建一个容器并初始化。然后,使用add函数添加三个字符串。最后,使用print函数打印容器中的所有字符串。
原文地址: https://www.cveoy.top/t/topic/oUiB 著作权归作者所有。请勿转载和采集!