源码
#include <stdio.h>
#include <stdlib.h>
typedef int E;
struct ListNode {
E element;
struct ListNode *next;
struct ListNode *prev;
};
typedef struct ListNode *Node;
void initList(Node head) {
head->next = head->prev = head;
}
_Bool insertList(Node head, E element, int index) {
if (index < 1) return 0;
while (--index && head->next != head) {
head = head->next;
}
Node node = malloc(sizeof(struct ListNode));
if (node == NULL) return 0;
node->element = element;
node->next = head->next;
head->next->prev = node;
head->next = node;
node->prev = head;
if (node->next == head) {
head->prev = node;
}
return 1;
}
int deleteList(Node head, int index) {
if (index < 1) return 0;
while (--index && head->next != head) {
head = head->next;
}
if (head->next == head) return 0;
Node tem = head->next;
tem->next->prev = head;
head->next = tem->next;
free(tem);
if (head->next == head) {
head->prev = head;
} else {
head->next->prev = head;
}
return 1;
}
int main(void) {
struct ListNode head;
initList(&head);
for (int i = 0; i < 5; i++) {
insertList(&head, i + 1, i + 1);
}
deleteList(&head, 4);
Node node = head.next;
do {
printf("%d -> ", node->element);
node = node->next;
} while (node != &head);
printf("\n");
node = head.prev;
do {
printf("%d -> ", node->element);
node = node->prev;
} while (node != &head);
printf("\n");
return 0;
}