C实现带头双向循环链表
头文件:
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<assert.h> #include<stdlib.h> typedef int LTDataType; typedef struct ListNode { LTDataType a; struct ListNode* prev; struct ListNode* next; }ListNode; //创建返回链表的头节点 ListNode* ListCreat(); //销毁 void ListDestory(ListNode* plist); //打印 void ListPrint(ListNode* plist); //尾插 void ListPushBack(ListNode* plist, LTDataType val); //尾删 void ListPopBack(ListNode* plist); //创建节点 ListNode* BuyListNode(LTDataType val); //头插 void ListPushFront(ListNode* plist, LTDataType val); //头删 void ListPopFront(ListNode* plist); //查找 LTDataType ListFind(ListNode* head, LTDataType val); //在pos的位置插入(前插) void ListInsert(ListNode* pos, LTDataType x, LTDataType val); //删除pos的节点(前删) void ListErase(ListNode* pos, LTDataType x);
实现:
#include"LIstNode.h" //创建返回链表的头节点 ListNode* ListInit() { ListNode* head = (ListNode*)malloc(sizeof(ListNode)); head->next = head; head->prev = head; return head; } //销毁 void ListDestory(ListNode* head) { assert(head); ListNode* cur = head->next; while (cur!= NULL || cur->next != NULL) { ListNode* _next = cur->next; free(cur); cur = _next; } free(head); head->a = 0; head->next = NULL; head->prev = NULL; } //打印 void ListPrint(ListNode* head) { assert(head); ListNode* cur =head->next; while (cur != NULL) { printf("%d ", cur->a); cur = cur->next; } } //尾插 void ListPushBack(ListNode* head, LTDataType val) { assert(head); ListNode* New = BuyListNode(val); ListNode* tail = head->prev; tail->next = New; New->next = head; New->prev = tail; tail = New; } //创建节点 ListNode* BuyListNode(LTDataType val) { ListNode* NewHead = (ListNode*)malloc(sizeof(ListNode)); NewHead->a = val; NewHead->next = NULL; NewHead->prev = NULL; return NewHead; } //尾删 void ListPopBack(ListNode* head) { ListNode* tail = head->prev; head->prev = tail->prev; tail->prev->next = head; tail = head->prev; } //头插 void ListPushFront(ListNode* head, LTDataType val) { ListNode* cur = head->next; ListNode* New = BuyListNode(val); head->next = New; New->prev = head; New->next = cur; cur->prev = New; } //头删 void ListPopFront(ListNode* head) { ListNode* cur = head->next; ListNode* _next = cur->next; head->next = _next; _next->prev = head; } //查找 LTDataType ListFind(ListNode* head, LTDataType val) { ListNode* cur = head->next; int count = 1; while (cur != NULL) { if (cur->a == val) return count; cur = cur->next; ++count; } return -1; } //在pos的位置插入(前插) void ListInsert(ListNode* pos, LTDataType x, LTDataType val) { ListNode* New = BuyListNode(val); int count = 1; ListNode* cur = pos->next; while (count < x) { cur = cur->next; ++count; } New->prev = cur->prev; cur->prev->next = New; New->next = cur; cur->prev = New; } //删除pos的节点(前删) void ListErase(ListNode* pos, LTDataType x) { int count = 1; ListNode* cur = pos->next; while (count < x) { cur = cur->next; ++count; } cur->prev = cur->prev->prev; cur->prev->next = cur; }