感谢UP主[TyrantLucifer]分享的视频,参考B站www.bilibili.com/video/BV1W6…
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct Node {
int data;
struct Node* next;
}Node;
Node* initList() {
Node* L = (Node*)malloc(sizeof(Node));
L->data = 0;
L->next = L;
return L;
}
void headInsert(Node* L, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = L->next;
L->next = node;
L->data++;
}
void tailInsert(Node* L, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
Node* n = L;
while (n->next != L) {
n = n->next;
}
n->next = node;
node->next = L;
}
int delete(Node* L, int data) {
Node* pre = L;
Node* cur = L->next;
while (cur != L) {
if (cur->data == data) {
pre->next = cur->next;
free(cur);
return TRUE;
}
pre = cur;
cur = cur->next;
}
return FALSE;
}
void printList(Node* L) {
Node* node = L->next;
while (node != L) {
printf("%d->", node->data);
node = node->next;
}
printf("NULL\n");
}
int main(void) {
Node* L = initList();
headInsert(L, 1);
headInsert(L, 2);
headInsert(L, 3);
headInsert(L, 4);
printList(L);
tailInsert(L, 5);
tailInsert(L, 6);
tailInsert(L, 7);
printList(L);
delete(L, 5);
printList(L);
return 0;
}