#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef int DListDate;
typedef struct DListNode{
struct DListNode* next;
struct DListNode* prev;
DListDate date;
}DListNode;
DListNode* BuyDListnode(DListDate x);//增加新节点
DListNode* DListinit(); //初始化
void DListPushBack(DListNode* phead, DListDate x);//尾插
void DListPopBack(DListNode* phead);//尾删
void DListPushfrot(DListNode* phead, DListDate x);//头插
void DListPopfrot(DListNode* phead);// 头删
void printDListnode(DListNode* phead); //打印链表
DListNode* ListFind(DListNode* phead, DListDate x); //查找
void ListInsert(DListNode* pos, DListDate x, DListDate a); //插入
void ListErase(DListNode* pos, DListDate x); //中间删除
DListNode* BuyDListnode(DListDate x)//增加新节点
{
DListNode* newnode = (DListNode*)malloc(sizeof(DListNode));
newnode->next = NULL;
newnode->prev = NULL;
newnode->date = x;
return newnode;
}
DListNode* DListinit() //初始化
{
DListNode* phead = BuyDListnode(0);
phead->next = phead;
phead->prev = phead;
return phead;
}
void DListPushBack(DListNode* phead, DListDate x)//尾插
{
DListNode* newnode = BuyDListnode(x);
if(phead == NULL){
phead = newnode;
}
else{
DListNode* tail = phead->prev;
tail->next = newnode;
newnode->prev = tail;
newnode->next = phead;
phead->prev = newnode;
}
}
void printDListnode(DListNode* phead) //打印链表
{
DListNode* cur = phead->next;
while(cur != phead)
{
printf("%d ",cur->date);
cur = cur->next;
}
printf("\n");
}
void DListPopBack(DListNode* phead)//尾删
{
assert(phead);
DListNode* tail = phead->prev;
tail->prev->next = phead;
phead->prev = tail->prev;
free(tail);
}
void DListPushfrot(DListNode* phead, DListDate x)//头插
{
DListNode* newnode = BuyDListnode(x);
DListNode* head = phead->next;
head->prev = newnode;
newnode->prev = phead;
phead->next = newnode;
newnode->next = head;
}
void DListPopfrot(DListNode* phead)// 头删
{
DListNode* cur = phead->next;
phead->next = cur->next;
cur->next->prev = phead;
free(cur);
}
DListNode* ListFind(DListNode* phead, DListDate x) //查找
{
DListNode* cur = phead->next;
while(cur != phead)
{
if(cur->date = x)
{
return cur;
}
cur = cur->next;
}
return NULL;
}
int main(int argc, char *argv[]) {
DListNode* phead = DListinit();
DListPushBack(phead, 0);
DListPushBack(phead, 1);
DListPushBack(phead, 2);
DListPushBack(phead, 3);//尾插
DListPopBack(phead);//尾删
DListPushfrot(phead,-1);//头插
DListPopfrot(phead);//头删
printDListnode(phead);
return 0;
}
双向链表(代码)
最新推荐文章于 2024-07-22 20:42:52 发布