用c语言完整的定意一个链表,并写出操作函数
时间: 2024-10-09 09:03:39 浏览: 32
在C语言中,我们可以定义一个链表结构体、创建节点、以及添加、删除和遍历节点的基本操作。这里是一个简单的单向链表的定义及一些基本操作函数:
首先,定义链表节点结构体(Node):
```c
typedef struct Node {
int data; // 节点数据
struct Node* next; // 指向下一个节点的指针
} Node;
```
然后,定义链表的头结点(LinkedList):
```c
typedef struct LinkedList {
Node* head; // 链表头指针,初始为空
} LinkedList;
```
接下来是一些操作函数:
1. 初始化链表(创建新链表并设置头节点为NULL):
```c
void initializeList(LinkedList* list) {
list->head = NULL;
}
```
2. 添加新节点到链表头部:
```c
void insertAtBegining(LinkedList* list, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = list->head;
list->head = newNode;
}
```
3. 删除指定值的节点(如果存在):
```c
void deleteNode(LinkedList* list, int key) {
if (list->head == NULL) return;
if (list->head->data == key) {
Node* temp = list->head;
list->head = list->head->next;
free(temp);
return;
}
Node* current = list->head;
while (current->next != NULL && current->next->data != key) {
current = current->next;
}
if (current->next != NULL) {
Node* temp = current->next;
current->next = current->next->next;
free(temp);
}
}
```
4. 遍历链表打印所有元素:
```c
void printList(LinkedList* list) {
Node* current = list->head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
```
阅读全文