//带头节点的循环链表
//链表初始化
void InitList(CList plist)
{
assert(plist != NULL);
if(plist==NULL)
{
return ;
}
plist->next = plist;//plist->next = NULL;
}
//头插
bool Insert_head(CList plist,int val)
{
CNode *p = (CNode *)malloc(sizeof(CNode));
p->data = val;
p->next = plist->next;
plist->next = p;
return true;
}
//尾插
bool Insert_tail(CList plist,int val)
{
CNode *p = (CNode *)malloc(sizeof(CNode ));
p->data = val;
CNode *q;
for(q=plist;q->next!=plist;q=q->next) ;
//将p插入在q的后面
p->next = q->next;//p->next = plist;
q->next = p;
return true;
}
//查找
CNode *Srearch(CList plist,int key)
{
for(CNode *p=plist->next;p!=plist;p=p->next)
{
if(p->data == key)
{
return p;
}
}
return NULL;
}
//查找前驱
static CNode *SearchPri(CList plist,int key)
{
for(CNode *p=plist;p->next!=plist;p=p->next)
{
if(p->next->data == key)
{
return p;
}
}
return NULL;
}
//删除
bool Delete(CList plist,int key)
{
CNode *p = SearchPri(plist,key);
if(p == NULL)
{
return false;
}
CNode *q = p->next;
p->next = q->next;
free(q);
return true;
}
int GetLength(CList plist)
{
int count = 0;
for(CNode *p=plist->next;p!=plist;p=p->next)
{
count++;
}
return count;
}
bool IsEmpty(CList plist)
{
return plist->next == plist;
}
void Clear(CList plist)
{
Destroy(plist);
}
void Destroy(CList plist)
{
CNode *p;
while(plist->next != plist)//while(!IsEmpty(plist))
{
p = plist->next;
plist->next = p->next;
free(p);
}
}
void Show(CList plist)
{
for(CNode *p=plist->next;p!=plist;p=p->next)
{
printf("%d ",p->data);
}
printf("\n");
}