您的位置:首页 > 其它

简单实现双向循环链表

2009-11-27 13:41 531 查看
//本文来自于网络择录

转载http://lhtao31.blog.163.com/blog/static/2972647020093272222749/



#include <stdio.h>
#include <malloc.h>
//双向循环链表的操作

typedef struct node
{
struct node *prevList;
int value;
struct node *nextList;
} Node,*pNode;

//创建一个链表
pNode CreatList(void)
{
pNode head=NULL;
pNode newList=NULL;
pNode tmpList=NULL;
int val;
int i,n;

head=(pNode)malloc(sizeof(Node));
head->nextList=NULL;
head->prevList=NULL;
head->value=0;

if (head==NULL)
{
printf("malloc fail/n");
return NULL;
}

printf("请输入要创建的链表数:");
scanf("%d",&n);
tmpList=head;
for (i=0; i<n; i++)
{
newList=(pNode)malloc(sizeof(Node));

printf("请输入要插入的值:");
scanf("%d",&val);
newList->value=val;

tmpList->nextList=newList;
newList->prevList=tmpList;
newList->nextList=NULL;
tmpList=newList;
}
head->prevList=tmpList;
tmpList->nextList=head;
return head;
}

//查找等于特定值的链表
pNode SearchNode(pNode head)
{
pNode tmpList=NULL;
int val;

printf("请输入要查找的值:");
scanf("%d",&val);
tmpList=head->nextList;

while(tmpList != head)
{
if (tmpList->value == val)
{
printf("find list !/n");
return tmpList;
}
else
{
tmpList = tmpList->nextList;
}
}
printf("Not find !/n");
return NULL;
}

//在链表前插入一个节点
void InsertNode(pNode tmpList)
{
pNode newList=NULL;
int val;

if(tmpList==NULL)
{
printf("cannot insert null list /n");
return;
}
newList=(pNode)malloc(sizeof(Node));

if (newList == NULL)
{
printf("malloc fail /n");
}

printf("请输入你要插入的数值:");
scanf("%d",&val);
newList->value=val;
tmpList->prevList->nextList = newList;
tmpList->prevList=newList;
newList->nextList=tmpList;

}

//删除一个节点
void DelNode(pNode tmpList)
{
if (tmpList == NULL)
{
printf("cannot delete null node /n");
return;
}

(tmpList->prevList)->nextList = tmpList->nextList;
(tmpList->nextList)->prevList = tmpList->prevList;
free(tmpList);
}

//打印链表值和链表地址
void PrintfList(pNode head)
{
pNode tmpList=head->nextList;

printf("List Value %d,pre addr 0x%5x,current addr 0x%5x,next addr 0x%5x/n",head->value,head->prevList,head,head->nextList);
while (tmpList != head)
{
printf("Node Value %d,pre addr 0x%5x,current addr 0x%5x,next addr 0x%5x/n",tmpList->value,tmpList->prevList,tmpList,tmpList->nextList);
tmpList=tmpList->nextList;
}

}

void main()
{
pNode head=NULL;
pNode tmp=NULL;

head=CreatList(); //创建链表
PrintfList(head); //打印链表值以及地址
tmp=SearchNode(head); //查找一个节点
// InsertNode(tmp); //在这个值前插入一个节点
DelNode(tmp); //删除这个节点
PrintfList(head);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: