用c语言写一段代码,要求使用单链表的操作(新建,消除,定位,查找,插入,删除,修改,输出,判断空,满。)
时间: 2024-09-17 16:08:31 浏览: 44
C语言之单链表的插入、删除与查找
在C语言中,我们可以使用结构体来表示单链表节点,并编写相应的函数来操作这个链表。下面是一个简单的示例,包含了创建、查找、插入、删除等基本操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建新节点并分配内存
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 插入节点到链表末尾
void insertNode(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 查找并返回特定值的节点指针
Node* findNode(Node* head, int target) {
Node* current = head;
while (current != NULL) {
if (current->data == target) {
return current;
}
current = current->next;
}
return NULL; // 如果未找到,返回NULL
}
// 删除指定节点
void deleteNode(Node** head, int target) {
if (*head == NULL) return;
if ((*head)->data == target) { // 如果头节点就是目标
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
while (current->next != NULL && current->next->data != target) {
current = current->next;
}
if (current->next != NULL) {
Node* temp = current->next;
current->next = current->next->next;
free(temp);
}
}
// 输出链表元素
void printList(Node* head) {
if (head == NULL) {
printf("List is empty.\n");
} else {
Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
}
int main() {
Node* head = NULL;
// ... 对链表进行其他操作 ...
return 0;
}
```
阅读全文