单链表实现增删改查c语言
时间: 2023-10-23 08:10:07 浏览: 48
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
void insertFront(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void insertAfter(struct Node* prev_node, int new_data) {
if (prev_node == NULL) {
printf("Previous node cannot be NULL\n");
return;
}
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
void insertEnd(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = (*head_ref);
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
return;
}
void deleteNode(struct Node** head_ref, int key) {
struct Node* temp = *head_ref, *prev;
if (temp != NULL && temp->data == key) {
*head_ref = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
if (temp == NULL)
return;
prev->next = temp->next;
free(temp);
}
void modifyNode(struct Node* node, int old_data, int new_data) {
while (node != NULL) {
if (node->data == old_data) {
node->data = new_data;
return;
}
node = node->next;
}
printf("%d not found in the list\n", old_data);
}
int main() {
struct Node* head = NULL;
insertEnd(&head, 1);
insertFront(&head, 2);
insertFront(&head, 3);
insertEnd(&head, 4);
insertAfter(head->next, 5);
printf("Original List: ");
printList(head);
deleteNode(&head, 3);
printf("List after deleting 3: ");
printList(head);
modifyNode(head, 2, 6);
printf("List after modifying 2 to 6: ");
printList(head);
return 0;
}