#include <stdio.h> #include <stdlib.h>

struct node { int data; struct node *next; };

typedef struct node Node;

Node *createNode(int data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL; return newNode; }

void insert(Node **head, int data) { Node *newNode = createNode(data); if (*head == NULL) { *head = newNode; return; } Node *current = *head; while (current->next != NULL) { current = current->next; } current->next = newNode; }

void delete(Node **head, int data) { if (*head == NULL) { return; } if ((*head)->data == data) { Node *temp = *head; *head = (*head)->next; free(temp); return; } Node *current = *head; while (current->next != NULL) { if (current->next->data == data) { Node *temp = current->next; current->next = temp->next; free(temp); return; } current = current->next; } }

void printList(Node *head) { if (head == NULL) { printf("List is empty.\n"); return; } Node *current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); }

int main() { Node *head = NULL; insert(&head, 10); insert(&head, 20); insert(&head, 30); printList(head); delete(&head, 20); printList(head); delete(&head, 10); printList(head); delete(&head, 30); printList(head); return 0; }

C语音写一个链表

原文地址: https://www.cveoy.top/t/topic/gV1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录