标签:size code 指针 无法 eof 补充 link free color
在单链表当中,从已知节点出发,只能访问该节点的后继节点,却无法访问
该节点之前的节点,在单循环链表当中,虽然可以通过一个节点访问表中所
有节点,但是要找到直接前驱却要遍历整个表,因此为了加快寻找某个节点
的前驱,可以在每个节点的结构体上添加一个直接访问前驱的指针域来快速
定位前驱节点。下面是简单的双链表代码,当然优势还没有体现出来,后面
在慢慢补充
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef struct Dbnode{
int data;
struct Dbnode * next;
struct Dbnode * prior;
} Dbnode, *Dblink;
typedef int ElemType;
typedef int Status;
Status initLink(Dblink * link,int num){
srand(time(0));
Dblink L = *link;
Dblink tmp,new;
L->data = 0;
L->prior = NULL;
L->next = NULL;
tmp = L;
int i;
for(i=0;i<num;i++){
new = (Dblink)malloc(sizeof(Dbnode));
new->data = rand()%100 +1;
new->next = tmp->next;
new->prior = tmp;
tmp->next = new;
tmp = tmp->next;
}
return OK;
}
Status insertLink(Dblink *link,int index,ElemType e){
Dblink tmp = (*link)->next; //ignore head node
Dblink new,pre;
int i=1;
while( tmp && i<index ){
tmp = tmp->next;
i++;
}
if( !tmp || i>index){
printf("overflow\n");
return OVERFLOW;
}
new = (Dblink)malloc(sizeof(Dbnode));
pre = tmp->prior;
new->data = e;
new->prior=pre;
new->next =tmp;
pre->next = new;
tmp->prior= new;
return OK;
}
Status deleteLink(Dblink *link,int index){
Dblink tmp = (*link)->next; //ignore head node
int i=1;
while( tmp && i<index ){
tmp=tmp->next;
i++;
}
if( !tmp || i>index ){
printf("overflow\n");
return OVERFLOW;
}
Dblink pre = tmp->prior;
Dblink net = tmp->next;
pre->next = tmp->next;
net->prior = tmp->prior;
free(tmp);
return OK;
}
Status printLink(Dblink link){
Dblink p = link;
while(p->next){
p = p->next; //ignore head node
printf("[%d] ",p->data);
}
printf("\n");
return OK;
}
int main(){
int num,index,value;
Dblink link = (Dblink)malloc(sizeof(Dbnode));
//initation
printf("[create]enter the num:");
scanf("%d",&num);
initLink(&link,num);
printLink(link);
//insert
printf("[insert]enter the index:");
scanf("%d",&index);
printf("[insert]enter the value:");
scanf("%d",&value);
insertLink(&link,index,value);
printLink(link);
//delete
printf("[delete]enter the index:");
scanf("%d",&index);
deleteLink(&link,index);
printLink(link);
return OK;
}
标签:size code 指针 无法 eof 补充 link free color
原文地址:http://www.cnblogs.com/demonxian3/p/7123461.html