用c语言实现链表字符串的增删改查操作
时间: 2024-02-01 07:13:08 浏览: 77
下面是用 C 语言实现链表字符串的增删改查操作的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 链表节点结构体
typedef struct ListNode {
char* str; // 字符串数据
struct ListNode* next; // 指向下一个节点的指针
} ListNode;
// 创建新节点
ListNode* createNode(char* str) {
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->str = (char*)malloc(strlen(str) + 1);
strcpy(node->str, str);
node->next = NULL;
return node;
}
// 在链表尾部添加节点
void addNode(ListNode** head, char* str) {
ListNode* node = createNode(str);
if (*head == NULL) {
*head = node;
} else {
ListNode* p = *head;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
}
}
// 在链表中查找节点并返回它的指针
ListNode* findNode(ListNode* head, char* str) {
ListNode* p = head;
while (p != NULL) {
if (strcmp(p->str, str) == 0) {
return p;
}
p = p->next;
}
return NULL;
}
// 在链表中删除节点
void deleteNode(ListNode** head, char* str) {
ListNode* p = *head;
ListNode* prev = NULL;
while (p != NULL) {
if (strcmp(p->str, str) == 0) {
if (prev == NULL) {
*head = p->next;
} else {
prev->next = p->next;
}
free(p->str);
free(p);
return;
}
prev = p;
p = p->next;
}
}
// 修改链表中的节点数据
void modifyNode(ListNode* node, char* str) {
free(node->str);
node->str = (char*)malloc(strlen(str) + 1);
strcpy(node->str, str);
}
// 输出链表中所有节点的字符串数据
void printList(ListNode* head) {
ListNode* p = head;
while (p != NULL) {
printf("%s ", p->str);
p = p->next;
}
printf("\n");
}
// 释放链表内存
void freeList(ListNode* head) {
ListNode* p = head;
while (p != NULL) {
ListNode* next = p->next;
free(p->str);
free(p);
p = next;
}
}
int main() {
ListNode* head = NULL;
addNode(&head, "hello");
addNode(&head, "world");
addNode(&head, "foo");
addNode(&head, "bar");
printf("Initial list: ");
printList(head);
ListNode* node = findNode(head, "world");
if (node != NULL) {
printf("Found node with data 'world'\n");
modifyNode(node, "new");
}
deleteNode(&head, "foo");
printf("After modification and deletion: ");
printList(head);
freeList(head);
return 0;
}
```
输出结果如下:
```
Initial list: hello world foo bar
Found node with data 'world'
After modification and deletion: hello new bar
```
阅读全文