再写双向循环链表
#pragma once
#include<assert.h>
#include<malloc.h>
#include<stdio.h>
typedef int DLDataType;//定義鏈表結點結構
typedef struct DListNode{DLDataType value;struct DListNode *prev; //指向前一個結點struct DListNode *next; //指向后一個結點
} DListNode;//定義雙向鏈表結構
typedef struct DList{DListNode *head; //表示鏈表頭結點
}DList;DListNode *DListBuyNode(DLDataType value){DListNode *node = (DListNode *)malloc(sizeof (DListNode));node->value = value;node->next =node->prev= NULL;return node;
}//初始化
void DListInit(DList *dlist){dlist->head = DListBuyNode(0);dlist->head->next = dlist->head;dlist->head->prev = dlist->head;
}//銷毀
//1. 清空鏈表
void DListClear(DList *dlist){DListNode *cur, *next;cur = dlist->head->next;while (cur != dlist->head){next = cur->next;free(cur);cur = next;}dlist->head->next = dlist->head->prev = dlist->head;
}//2. 徹底銷毀鏈表
void DListDestroy(DList *dlist){DListClear(dlist);free(dlist->head);dlist->head = NULL;
}//頭插
void DListPushFront(DList *dlist, DLDataType value){DListNode *node = DListBuyNode(value);node->prev = dlist->head;node->next = dlist->head->next;dlist->head->next->prev = node;dlist->head->next = node;}//尾插
void DlistPushBack(DList *dlist, DLDataType value){DListNode *node = DListBuyNode(value);node->prev = dlist->head->prev;node->next = dlist->head;node->prev->next = node;node->next->prev = node;
}//頭刪
void DlistPopFront(DList *dlist){assert(dlist->head->next != dlist->head);DListNode *cur = dlist->head->next; //cur指向第一個結點dlist->head->next = cur->next; //頭結點指向第二個結點cur->next->prev = dlist->head; //第二個結點前指針指向頭結點free(cur); //刪除第一個結點
}//尾刪
void DlistPopBack(DList *dlist){assert(dlist->head->next != dlist->head); //確保鏈表不為空DListNode *cur = dlist->head->prev;cur->prev->next = dlist->head;cur->next->prev = cur->prev;free(cur);
}//查找
DListNode * DListFind(const DList *dlist, DLDataType value){DListNode *cur;for (cur = dlist->head->next; cur != dlist->head; cur = cur->next){if (cur->value == value){return cur;}}return NULL;
}void DListInsert(DListNode *pos, DLDataType value){DListNode *node = DListBuyNode(value);node->prev = pos->prev;node->next = pos;node->prev->next = node;pos->prev = node;
}void DListErase(DListNode *pos){pos->prev->next = pos->next;pos->next->prev = pos->prev;free(pos);
}void DListPrintf(const DList *dlist){for (DListNode *cur = dlist->head->next; cur != dlist->head; cur = cur->next){printf("%d-->", cur->value);}printf("\n");
}void TestDList(){DList list;DListInit(&list);DListPrintf(&list);DlistPushBack(&list, 1);DlistPushBack(&list, 2);DlistPushBack(&list, 3);DListPrintf(&list);DListPushFront(&list, 11);DListPushFront(&list, 12);DListPushFront(&list, 13);DListPrintf(&list);
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
- 上一篇: DNF阿修罗怎么样.
- 下一篇: 链表题目--1 删除链表中所有等于v