sunzl1987

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

作为一个C开发人员,无论在求职笔试题中,还是在工程项目中,都会遇到用c语言创建双向环形链表。这个也是理解和使用c指针的一项基本功。

#include<...>//头文件省略

typedef struct ringbuf_str
{
unsigned int ringID; /* ring ID*/
struct ringbuf_str *next; /* Next ringbuf in list */
struct ringbuf_str *pre; /* Previous ringbuf in list */
} RINGBUF_T;

RINGBUF_T *Init_Ringbuf(int len)
{
RINGBUF_T *pCurrent=null;
RINGBUF_T *pHead=null;
RINGBUF_T *pPrevious=null;
int i=0;

//@1.创建链表头pHead
pCurrent = (RINGBUF_T *)calloc(sizeof(RINGBUF_T),1);
if(pCurrent == null)
{
return null;
}
pHead = pCurrent;
pPrevious = pCurrent;
//初始化表头内容
pHead->pre = pCurrent;
pHead->next = pCurrent;
pHead->ringID = 0;

//@2.创建链表体.
for(i=1;i<len;i++)
{
pCurrent = (RINGBUF_T *)calloc(sizeof(RINGBUF_T),1);
if(pCurrent == null)
{
return null;
}

pPrevious->next = pCurrent;
pCurrent->pre = pPrevious;
pCurrent->ringID = i;

pPrevious = pCurrent;
}
//@3.链表首尾相接,形成环形链表
pHead->pre = pCurrent;
pCurrent->next = pHead;

return(pHead);
}
//删除链表
int Release_Ringbuf(RINGBUF_T *ringbuff,int len)
{
RINGBUF_T *pCurrent = null;
RINGBUF_T *pPrevious = null;
int i = 0;

if(ringbuff == null)
return -1;

pCurrent = ringbuff;

for(i=0;i<len; i++)
{
pPrevious = pCurrent;
pCurrent = pCurrent->next;
free(pPrevious);
}
pCurrent = IC_NULL;
pPrevious = IC_NULL;

return 0;
}
//main函数
int main(void)
{
#define RINGBUFFLEN 10
RINGBUF_T *ringbuff=null;

//@1.初始化一个链表,长度为RINGBUFFLEN
ringbuff=Init_Ringbuf(RINGBUFFLEN);

//@2. do some operations
//...

//@3.释放该链表
Release_Ringbuf(ringbuff,RINGBUFFLEN);

return 0;
}

posted on 2014-11-18 15:54  Sanz  阅读(483)  评论(0编辑  收藏  举报