XList.h如下:
#ifndef __LIST_H
#define __LIST_H
typedef struct LNode
{
int data;
struct LNode* next;
struct LNode* pre;
}LNode, *List;
void InitList(List list);//初始化化单链表
void Insert_Head(List list, int var);//头插节点
void Insert_Tail(List list, int var);//尾插节点
LNode *Search(List list, int key);//查找key
LNode *SearchPre(List list, int key);//查找key的前驱
bool Delete(List list, int key);//删除key
bool isEmpty(List list);//是否为空
int Length(List list);//返回链表的数据节点个数
void Show(List list);//打印
void Destroy(List list);//删除list所有数据节点
#endif
XList.c如下:
</pre><pre name="code" class="cpp">#include"XList.h"
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
static LNode* BuyNode(int val)
{
LNode *p = (LNode*)malloc(sizeof(LNode));
assert(p != NULL);
p->data = val;
p->next = NULL;
p->pre = NULL;
return p;
}
void InitList(List list)//初始化化单链表
{
assert(list);
list->next = list;
list->pre = list;
}
void Insert_Head(List list, int var)//头插节点
{
LNode *p = BuyNode(var);
LNode *tmp = list;
p->next = list->next;
//list->next->pre = p;//多余了
p->pre = list;
list->next = p;
while (tmp->next != list)
tmp = tmp->next;
list->pre = tmp;
}
void Insert_Tail(List list, int var)//尾插节点
{
LNode *last = list;
LNode *p = BuyNode(var);
while (last->next != list)
last = last->next;
last->next = p;
p->pre = last;
p->next = list;
list->pre = p;
}
LNode *Search(List list, int key)//查找key
{
LNode* p = list->next;
while (p!= list)
{
if (p->data == key)
return p;
p = p->next;
}
return NULL;
}
LNode *SearchPre(List list, int key)//查找key的前驱
{
LNode* p = list->next;
while (p!= list)
{
if (p->data == key)
return p->pre;
p = p->next;
}
return NULL;
}
bool Delete(List list, int key)//删除key
{
LNode* p = Search(list, key);
if (p == NULL)
return false;
p->next->pre = p->pre;
p->pre->next = p->next;
free(p);
return true;
}
bool isEmpty(List list)//是否为空
{
if (list->next = list)
return true;
return false;
}
int Length(List list)//返回链表的数据节点个数
{
int count = 0;
LNode* p = list;
while (p->next != list)
{
count++;
p = p->next;
}
return count;
}
void Show(List list)//打印
{
LNode* p = list;
while (p->next != list)
{
printf("%d ", p->next->data);
p = p->next;
}
printf("\n");
}
void Destroy(List list)//删除list所有数据节点
{
LNode* p = list->next;
LNode* t = p;
while (p!= list)
{
p->next->pre = p->pre;
p->pre->next = p->next;
t = p;
free(t);
}
free(list);
}