用c语言实现单链表操作
时间: 2023-05-11 16:07:43 浏览: 135
可以使用以下代码实现单链表操作:
```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));
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;
}
}
void deleteNode(Node **head, int data) {
if (*head == NULL) {
return;
}
Node *current = *head;
if (current->data == data) {
*head = current->next;
free(current);
return;
}
while (current->next != NULL && current->next->data != data) {
current = current->next;
}
if (current->next == NULL) {
return;
}
Node *temp = current->next;
current->next = temp->next;
free(temp);
}
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node *head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
printList(head);
deleteNode(&head, 2);
printList(head);
return 0;
}
```
这段代码实现了单链表的创建、插入、删除和打印操作。
阅读全文