#include<stdio.h> #include<stdlib.h> // 双向链表 typedef struct DoubleNode { int data; struct DoubleNode * pre, * next; }Node; void PrintList(Node * head) { Node * cur = head->next; while(cur != head) { printf(" %d ", cur->data); cur = cur->next; } printf("\n"); } int LenList(Node * head) { Node * cur = head->next; int n; while(cur != head) { cur = cur->next; n++; } return n; } // 创建链表 Node * CreateList() { Node * head = (Node*) malloc (sizeof(Node)); if (NULL == head) exit(-1); head->next = head; head->pre = head; return head; } // 增 void InsertList(Node * head, int data) { Node * cur = (Node*) malloc (sizeof(Node)); if (NULL == cur) exit(-1); cur->data = data; cur->next = head->next; head->next = cur; // cur->pre = head; 可以 // cur->pre->next = cur; 不可以 cur->pre = head->pre; cur->next->pre = cur; } // 删 void DeleteList1(Node * head, int data) { Node * cur = head->next; while(cur != head) { if (cur->data == data) { cur->pre->next = cur->next; cur->next->pre = cur->pre; free(cur); } cur = cur->next; } } // 销毁 void DestoryList(Node * head) { head->pre->next = NULL; Node * cur; while(head) { cur = head; head = head->next; free(cur); } } int main() { printf("创建链表:\n"); Node * head = CreateList(); PrintList(head); printf("插入链表:\n"); int i; for(i=0; i<100; i+=10) { InsertList(head, i); } PrintList(head); printf("删除链表:\n"); DeleteList(head, 40); PrintList(head); DestoryList(head);
原文:https://www.cnblogs.com/oytt/p/13637399.html