请用c语言编程一个对单链表进行基本操作的系统,主要包括表的创建,插入,删除,查询,取值,输出,删除等操作,采用带头节点的单链表
时间: 2024-05-25 14:16:43 浏览: 98
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* create_list() {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
return head;
}
void insert_node(Node* head, int data) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = head->next;
head->next = new_node;
}
void delete_node(Node* head, int data) {
Node* p = head->next;
Node* pre = head;
while (p) {
if (p->data == data) {
pre->next = p->next;
free(p);
return;
}
pre = p;
p = p->next;
}
}
Node* find_node(Node* head, int data) {
Node* p = head->next;
while (p) {
if (p->data == data) {
return p;
}
p = p->next;
}
return NULL;
}
int get_node_data(Node* head, int index) {
Node* p = head->next;
int i = 0;
while (p && i < index) {
p = p->next;
i++;
}
if (p && i == index) {
return p->data;
}
return -1;
}
void print_list(Node* head) {
Node* p = head->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void destroy_list(Node* head) {
Node* p = head->next;
while (p) {
Node* q = p->next;
free(p);
p = q;
}
free(head);
}
int main() {
Node* head = create_list();
insert_node(head, 1);
insert_node(head, 2);
insert_node(head, 3);
print_list(head);
delete_node(head, 2);
print_list(head);
Node* p = find_node(head, 3);
if (p) {
printf("%d\n", p->data);
}
printf("%d\n", get_node_data(head, 1));
destroy_list(head);
return 0;
}
阅读全文