双链表(带头节点,头节点数据域为节点数)
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* pre;
struct Node* next;
}Node;
Node* initDoubleLinkList() {
Node* list = (Node*)malloc(sizeof(Node));
list->data = 0;
list->pre = NULL;
list->next = NULL;
}
void headPush(Node* list, int data) {
Node* n = (Node*)malloc(sizeof(Node));
n->data = data;
n->next = list->next;
n->pre = list;
if (list->next) {
list->next->pre = n;
}
list->next = n;
list->data++;
}
void tailPush(Node* list, int data) {
Node* n = (Node*)malloc(sizeof(Node));
Node* temp = list;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = n;
n->data = data;
n->pre = temp;
n->next = NULL;
list->data++;
}
int delete(Node* list, int data) {
Node* temp = list->next;
while (temp) {
if (temp->data == data) {
temp->pre->next = temp->next;
if (temp->next) {
temp->next->pre = temp->pre;
}
list->data--;
free(temp);
return 1;
}
temp = temp->next;
}
return 0;
}
void print(Node* list) {
Node* temp = list->next;
while (temp) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
void test() {
Node* list = initDoubleLinkList();
headPush(list, 9);
headPush(list, 8);
headPush(list, 7);
print(list);
tailPush(list, 1);
tailPush(list, 2);
tailPush(list, 3);
print(list);
delete(list, 8);
print(list);
delete(list, 2);
print(list);
}
int main() {
test();
return 0;
}