typedef struct NODE {
struct NODE *link;
int value;
} Node;
typedef struct DNODE {
struct DNODE *fwd;
struct DNODE *bwd;
int value;
} Dnode;
# s11_node.h ###############
#include <stdio.h>
#include <stdlib.h>
#include "s11_node.h"
#define FALSE 0
#define TRUE 1
int d11_insert(register Dnode *proot,int value){
register Dnode *this;
register Dnode *next;
register Dnode *newnode;
/**
* 查查value是否存在链表中,如果是就直接返回
* 否则为值创建一个新节点(“newnode”将指向它)
* this指向新节点之前那个节点
* next指向新节点之后那个节点
*/
for(this=proot; (next = this->fwd) != NULL; this = next){
if (next->value == value)
return FALSE;
if(next->value > value)
break;
}
newnode = (Dnode *)malloc(sizeof(Dnode));
if(newnode == NULL)
return FALSE;
newnode->value = value;
/*新节点添加到链表中*/
newnode->fwd = next;
this->fwd = newnode;
if(this != proot)
newnode->bwd = this;
else
newnode->bwd = NULL;
if(next != NULL)
next->bwd = newnode;
else
proot->bwd = newnode;
return TRUE;
}
/**
* 单向链表有序插入
*/
int s11_insert(register Node **plink, int new_value)
{
register Node *current;
register Node *new;
/*寻找正确的插入位置*/
while((current = *plink) != NULL && current->value < new_value){
plink = ¤t->link;
}
/*为新节点分配内存*/
new = (Node *)malloc(sizeof(Node));
if(new == NULL){
return FALSE;
}
new->value = new_value;
/*链表中插入新节点*/
new->link = current;
*plink = new;
return TRUE;
}
int main(int argc, char **argv)
{
Node *p1;
p1 = NULL;
int i;
for(i=0;i<20;i+=2)
s11_insert(&p1,i);
s11_insert(&p1, 15);
while(p1!=NULL){
printf("%d\n",p1->value);
p1 = p1->link;
}
return EXIT_SUCCESS;
}
# main.c ######
【C】单向链表和双向链表的插入
最新推荐文章于 2021-09-22 19:26:26 发布