C语言实现链表头部插入一个节点,尾部插入一个节点,删除指定值的节点,查找链表中是否存在指定值的节点,打印链表中额所有节点值
时间: 2024-11-12 11:43:39 浏览: 23
在C语言中,我们通常会使用结构体来表示链表节点,包含数据域和指向下一个节点的指针。以下是基本操作的示例:
1. **头部插入**:
```c
struct Node {
int data;
struct Node* next;
};
void insertAtHead(struct Node** head, int value) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = *head;
// 更新头指针
*head = newNode;
}
```
2. **尾部插入**:
```c
void insertAtTail(struct Node** head, int value) {
if (*head == NULL) { // 如果链表为空,直接插入
insertAtHead(head, value);
return;
}
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = (struct Node*)malloc(sizeof(struct Node)); // 插入点
current->next->data = value;
current->next->next = NULL; // 将新节点设置为尾节点
}
```
3. **删除指定值的节点**:
```c
void deleteNode(struct Node** head, int value) {
struct Node* temp = *head;
struct Node* prev = NULL;
if (temp != NULL && temp->data == value) {
*head = temp->next; // 如果头节点就是目标值,更新头指针
free(temp); // 释放原头节点
return;
}
while (temp != NULL && temp->data != value) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return; // 没找到对应值,返回
prev->next = temp->next;
free(temp); // 释放该节点
}
```
4. **查找指定值的节点**:
```c
struct Node* findNode(struct Node* head, int value) {
struct Node* current = head;
while (current != NULL) {
if (current->data == value)
return current;
current = current->next;
}
return NULL; // 没找到指定值
}
```
5. **打印链表所有节点值**:
```c
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
```
阅读全文