typedef struct NODE{
struct NODE *fwd;
struct NODE *bwd;
int value;
}Node;
双链表的根节点的bwd指针指向双链表的最后一个节点,fwd指针指向双链表的第一个节点,双链表的value字段为空
以下程序是将一个值插入到一个有序的双链表中,如果链表中已经有和该值相同的节点则不插入
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE{
struct NODE *bwd;
struct NODE *fwd;
int value;
}Node;
bool insert(Node *Rootnode,int newvalue);
bool insert(Node *Rootnode,int newvalue)
{
Node temnode;
int i = 0;
temnode = Rootnode;
Node *newnode = (Node*)malloc(sizeof(Node));
if(newnode ==NULL)
{
printf("malloc fail");
return false;
}
newnode->value = newvalue;
if (Rootnode->bwd == NULL)
{
Rootnode->bwd = newnode;
Rootnode->fwd = newnode;
return true;
}
for(;temnode->fwd != NULL;temnode = temnode->fwd)
{
i++;
if (temnode->value == newvalue)
{
printf("newvalue is already in double link list");
return true;
}
if (temnode->value > newvalue)
{
if (i==1)
{
newnode->fwd = Rootnode->fwd;
Rootnode->fwd = newnode;
newnode->bwd = Rootnode;
newnode->fwd->bwd=newnode;
}
else
{
temnode = temnode->bwd;
newnode->fwd = temnode->fwd;
temnode->fwd = newnode;
newnode->bwd = temnode;
newnode->fwd->bwd=newnode;
}
}
else
{
temnode = temnode->bwd;
newnode = temnode->fwd;
newnode->bwd = temnode;
}
}
return true;
}