写一个能够实现链表功能的代码
时间: 2024-03-11 09:48:41 浏览: 17
好的,这里是一个简单的链表实现的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct node {
int data; // 节点数据
struct node *next; // 指向下一个节点的指针
} Node;
// 创建一个新节点
Node *createNode(int data) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
return node;
}
// 在链表头部插入一个节点
void insertAtHead(Node **head, int data) {
Node *node = createNode(data);
node->next = *head;
*head = node;
}
// 在链表尾部插入一个节点
void insertAtTail(Node **head, int data) {
Node *node = createNode(data);
if (*head == NULL) {
*head = node;
} else {
Node *tail = *head;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = node;
}
}
// 在链表中删除一个节点
void deleteNode(Node **head, int data) {
Node *prev = NULL;
Node *curr = *head;
while (curr != NULL && curr->data != data) {
prev = curr;
curr = curr->next;
}
if (curr != NULL) {
if (prev == NULL) {
*head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
}
}
// 打印链表
void printList(Node *head) {
Node *curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
Node *head = NULL;
// 在链表头部插入节点
insertAtHead(&head, 1);
insertAtHead(&head, 2);
insertAtHead(&head, 3);
printf("在链表头部插入节点后:");
printList(head);
// 在链表尾部插入节点
insertAtTail(&head, 4);
insertAtTail(&head, 5);
insertAtTail(&head, 6);
printf("在链表尾部插入节点后:");
printList(head);
// 删除节点
deleteNode(&head, 3);
printf("删除节点后:");
printList(head);
return 0;
}
```
这个程序定义了一个链表节点结构体,包括节点的数据和指向下一个节点的指针。在主函数中,我们可以使用insertAtHead、insertAtTail和deleteNode函数来插入和删除节点,使用printList函数来打印整个链表。需要注意的是,在插入节点时,需要传入头结点的指针的地址,以便在函数中修改头结点的指针。