//doubleLinkList.c
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
/************************************************************************/
/* 双向非循环链表 */
/* 头节点前驱指针为空,尾节点后继指针为空 */
/* 头节点数据域为空,可存储链表节点个数 */
/************************************************************************/
typedef struct DulNode
{
int datafield; //数据域
struct DulNode *plink; //左指针
struct DulNode *nlink; //右指针
}DulNode, *DulLinkList;
/* 初始化链表
nodesize:链表的节点个数*/
DulLinkList init(int nodesize)
{
int i;
DulNode *prev, *head, *next;
if((head = (DulNode *)malloc(sizeof(DulNode))) == NULL)
{
printf("Malloc memory failure!");
exit(0);
}
head->datafield = 0;
head->plink = NULL;
head->nlink = NULL;
prev = head;
for (i = 0; i < nodesize; i++)
{
if ((next = (DulNode *)malloc(sizeof(DulNode))) == NULL)
{
printf("Malloc memory failure!");
exit(0);
}
prev->nlink = next;
printf("Please enter the %d node value:/t", i+1);
scanf("%d", &(next->datafield));
next->plink = prev;
next->nlink = NULL;
prev = next;
}
printf("/n");
return(head);
}
/*检索链表*/
DulLinkList retrieve(DulNode *head, int nodevalue)
{
DulNode *p;
p = head->nlink;
while(p != NULL)
{
if(p->datafield == nodevalue)
return(p);
else p = p->nlink;
}
printf("Can't retrieve any data!/n");
return NULL;
}
/*插入节点, p为检索后返回的节点*/
void insert(DulNode *p, int insertvalue)
{
DulNode *temp;
if ((temp = (DulNode *)malloc(sizeof(DulNode))) == NULL)
{
printf("Malloc memory failure!");
exit(0);
}
if(p->nlink == NULL)//如果插入的是尾节点
{
temp->datafield = insertvalue;
temp->nlink=NULL;
p->nlink=temp;
temp->plink=p;
}
else
{
temp->datafield = insertvalue;
temp->nlink=p->nlink;
p->nlink=temp;
temp->plink=p;
(temp->nlink)->plink=temp;
}
}
/*删除节点, p为检索后返回的节点*/
void delete(DulNode *p)
{
if (p->nlink == NULL)//如果删除的是尾节点
{
(p->plink)->nlink = NULL;
p->plink = NULL;
}
else
{
(p->nlink)->plink = p->plink;
(p->plink)->nlink = p->nlink;
}
free(p);
}
/*打印链表*/
void printNode(DulNode *head)
{
DulNode *p;
p = head->nlink;
printf("Nodes are:/t");
while (p != NULL)
{
printf("%d/t", p->datafield);
p = p->nlink;
}
printf("/n");
}
int main()
{
int a,b,c;
DulNode *head, *pretrieve;
//初始化
head = init(5);
//打印
printNode(head);
//检索
printf("Please enter the value you want to retrieve:/t");
scanf("%d",&a);
pretrieve = retrieve(head,a);
if(pretrieve != NULL)
{
printf("The value retrieved is :%d/n", pretrieve->datafield);
//插入
printf("Please enter the value you want to insert:/t");
scanf("%d",&b);
insert(pretrieve, b);
printf("The nodes after insert: /n");
printNode(head);
}
//删除
printf("/n");
printf("Please enter the value you want to delete:/t");
scanf("%d",&c);
pretrieve = retrieve(head,c);
if(pretrieve != NULL)
{
delete(pretrieve);
}
printf("The nodes after delete: /n");
printNode(head);
return 0;
}