#include<stdio.h>
#include<stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
//链表初始化
Node* initList() {
Node* list = (Node*)malloc(sizeof(Node));
list->data = 0;
list->next = NULL;
return list;
}
void headInsert(Node* list, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = list->next;
list->next = node;
list->data++;
}
void tailInsert(Node* list, int data) {
Node* head = list;
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
list = list->next;
while (list->next) {
list = list->next;
}
list -> next = node;
head -> data++;
}
void deleteList(Node* list, int data) {
Node* pre = list;
Node* current = list->next;
while (current) {
if (current->data == data) {
pre->next = current->next;
free(current);
break;
}
pre = current;
current = current->next;
}
list->data--;
}
void printList(Node* list) {
list = list->next;
while(list){
printf("%d", list->data);
list = list->next;
}
printf("\n");
}
int main() {
Node* list =initList();
//插入
headInsert(list, 1);
headInsert(list, 2);
headInsert(list, 3);
headInsert(list, 4);
headInsert(list, 5);
tailInsert(list, 6);
tailInsert(list, 7);
tailInsert(list, 8);
tailInsert(list, 9);
tailInsert(list, 10);
printList(list);
deleteList(list, 5);
//删除
deleteList(list, 10);
//打印
printList(list);
return 0;
}
数据结构单链表
最新推荐文章于 2024-09-24 21:14:08 发布