typedef int ElemType;
//双向链表节点数据结构
typedef struct DuLNode
{
DuLNode *prev;
DuLNode *next;
ElemType data;
}DuLNode;
//双向链表数据结构
typedef struct
{
DuLNode *head;
int size;
}DuList;
//购买一个节点
DuLNode * BuyNode(DuLNode *pr = NULL, DuLNode *nt = NULL)
{
DuLNode *s = (DuLNode*)malloc(sizeof(DuLNode));
if (NULL == s) exit(1);
s->prev = (pr == NULL) ? s : pr;
s->next = (nt == NULL) ? s : nt;
return s;
}
//获取链表长度
int getsize(DuList pr)
{
DuLNode *p = pr.head->next;
int i = 0;
while (p != NULL)
{
i++;
p = p->next;
}
return i;
}
//释放节点
void Freenode(DuLNode *p)
{
free(p);
}
//初始化链表
void InitDuList(DuList &Lt)
{
Lt.size = 0;
Lt.head = BuyNode();
}
//摧毁链表
void DestroyDuList(DuList &Lt)
{
DuLNode *p = Lt.head;
while (p != NULL)
{
Freenode(p);
p = p->next;
}
}
//获得值为x的节点的下标
int getindex(DuList Lt, ElemType x)
{
DuLNode *p = Lt.head->next;
int i = 0;
while (p != NULL)
{
i++;
if (p->data == x)
{
return i;
}
p = p->next;
}
return i;
}
//返回下标为i的节点
DuLNode* getnode(DuList Lt, int i)
{
DuLNode *p = Lt.head->next;
int n = 0;
while (n <= getsize(Lt))
{
n++;
if (n == i)
{
return p;
}
p = p->next;
}
}
//删除下标为i的节点
void DeleteDuList_index(DuList Lt, int i)
{
DuLNode *p = getnode(Lt, i);
p->next->prev = p->prev;
p->prev->next = p->next;
}
//删除值为val的节点
void DeleteDuList_val(DuList Lt,ElemType x)
{
int i = getindex(Lt, x);
if (i < 1 && i > getsize(Lt))
{
return;
}
DeleteDuList_index(Lt, i);
}
//在ptr前面插入一个节点
void Insert_Item_Prev(DuList &Lt, DuLNode *ptr, ElemType x)
{
ptr->prev = BuyNode(ptr->prev, ptr);
ptr = ptr->prev;
ptr->prev->next = ptr; // 4;
ptr->data = x;
Lt.size += 1;
}
//尾插
void Push_Back(DuList &Lt, ElemType x)
{
Insert_Item_Prev(Lt, Lt.head->prev, x);
}
//头插
void Push_Front(DuList &Lt, ElemType x)
{
Insert_Item_Prev(Lt, Lt.head->next, x);
}
校招复习——双向链表
最新推荐文章于 2024-08-24 23:54:19 发布