1.理论
2.C代码
/*************************************************************************
> File Name: list.c
> Author: NULL
> Mail: 574889524@qq.com
> Created Time: 2014年11月04日 星期二 20时09分03秒
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
/*双向循环链表,带哨兵(头节点)*/
struct sList{
int iValue;
struct sList *pNext;
struct sList *pPrev;
};
/*********************************************************/
void InitList(struct sList **ppList)
{
*ppList = (struct sList*)malloc(sizeof(struct sList));
(*ppList)->pNext = (*ppList)->pPrev = (*ppList);
/*相当于一个哨兵,其实就是我们所谓的头节点*/
}
void ExitList(struct sList **ppList)
{
struct sList *p = (*ppList)->pNext;
struct sList *q;
while(p!=(*ppList)){
q = p->pNext;
free(p);
p = q;
}
free(*ppList);
}
/*********************************************************/
/*查找第一个k元素 并返回指向k元素节点的指针*/
struct sList * ListSearch(struct sList *pHead,int k)
{
struct sList *p = pHead->pNext;
while(p!=pHead){
if(p->iValue == k)
return p;
else
p = p->pNext;
}
printf("Not find %d\n",k);
return NULL;/*没有找到k*/
}
/*插入的都在pHead后面的第一位*/
void ListInsert(struct sList *pHead,int x)
{
struct sList *p = NULL;
struct sList *pNode = (struct sList*)malloc(sizeof(struct sList));
pNode->iValue = x;
if(pHead->pNext == pHead){/*为空时*/
pNode->pPrev = pNode->pNext = pHead;
pHead->pNext = pHead->pPrev = pNode;
}else{
pNode->pPrev = pHead;
pHead->pNext->pPrev = pNode;
pNode->pNext = pHead->pNext;
pHead->pNext = pNode;
}
}
/*删除第一个元素是x的节点*/
int ListDelete(struct sList *pHead,int x)
{
struct sList *pNode = ListSearch(pHead,x);/*找到这个节点指针*/
if(!pNode){/*未找到*/
printf("list delete fail\n");
return -1;
}
/*说明只有一个元素,且要删除它*/
if(pNode->pNext == pHead && pHead->pNext==pNode){
pHead->pNext = pHead->pPrev = NULL;
free(pNode);
}else{
pNode->pPrev->pNext = pNode->pNext;
pNode->pNext->pPrev = pNode->pPrev;
free(pNode);
}
return 0;
}
int main()
{
int i;
struct sList *pList;
struct sList *p;
InitList(&pList);
for(i = 1;i<10;++i)
ListInsert(pList,i);
for(i=1;i<11;i++){
p = ListSearch(pList,i);
if(p != NULL)
printf("%d ",p->iValue);
}
ExitList(&pList);
return 0;
}