数据结构链表c语言
时间: 2023-06-21 22:21:04 浏览: 107
链表是一种数据结构,它由多个节点组成,每个节点包含了数据和指向下一个节点的指针。链表可以动态地增加或删除节点,因此非常适合需要频繁操作的场景。
下面是一个简单的链表的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 链表节点
struct Node {
int data; // 数据
struct Node* next; // 指向下一个节点的指针
};
// 创建节点
struct Node* createNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}
// 在链表末尾插入节点
void insertAtEnd(struct Node** head, int data) {
struct Node* node = createNode(data);
if (*head == NULL) {
*head = node;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = node;
}
}
// 在链表头部插入节点
void insertAtBeginning(struct Node** head, int data) {
struct Node* node = createNode(data);
node->next = *head;
*head = node;
}
// 删除链表中的节点
void deleteNode(struct Node** head, int data) {
struct Node* current = *head;
struct Node* prev = NULL;
while (current != NULL && current->data != data) {
prev = current;
current = current->next;
}
if (current == NULL) {
printf("Node with data %d not found\n", data);
return;
}
if (prev == NULL) {
*head = current->next;
} else {
prev->next = current->next;
}
free(current);
}
// 打印链表
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
insertAtBeginning(&head, 0);
printList(head);
deleteNode(&head, 2);
printList(head);
return 0;
}
```
这个程序定义了一个`Node`结构体表示链表节点,包含了数据`data`和指向下一个节点的指针`next`。函数`createNode`用来创建节点,函数`insertAtEnd`用来在链表末尾插入节点,函数`insertAtBeginning`用来在链表头部插入节点,函数`deleteNode`用来删除节点,函数`printList`用来打印链表。
在`main`函数中,我们创建了一个空链表`head`,然后依次插入了四个节点。最后打印链表,删除节点2,再次打印链表。
阅读全文
相关推荐












