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