用c语言写一个单链表
时间: 2024-09-14 13:06:21 浏览: 45
在C语言中,我们可以创建一个简单的单链表结构。这里是一个基本的单向链表节点定义、链表结构以及一些常用操作的例子:
```c
// 定义链表节点结构
typedef struct Node {
int data; // 节点数据
struct Node* next; // 指向下一个节点的指针
} Node;
// 创建链表
Node* createList() {
Node* head = NULL;
return head;
}
// 插入节点到链表头部
void insertAtHead(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
// 在特定位置插入节点
void insertAtPosition(Node** head, int position, int value) {
if (position <= 0) {
printf("Invalid position\n");
return;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
Node* current = *head;
for (int i = 0; i < position - 1 && current != NULL; ++i) {
current = current->next;
}
if (current == NULL) {
printf("Insertion position beyond the list.\n");
free(newNode);
return;
}
newNode->next = current->next;
current->next = newNode;
}
// 删除节点
void deleteNode(Node** head, int value) {
if (*head == NULL) {
return;
}
if ((*head)->data == value) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
while (current->next != NULL && current->next->data != value) {
current = current->next;
}
if (current->next == NULL) {
printf("Value not found in the list.\n");
return;
}
Node* temp = current->next;
current->next = current->next->next;
free(temp);
}
// 打印链表
void printList(Node* head) {
if (head == NULL) {
printf("Empty List\n");
} else {
Node* currentNode = head;
while (currentNode != NULL) {
printf("%d -> ", currentNode->data);
currentNode = currentNode->next;
}
printf("NULL\n");
}
}
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)