雙向鏈表代碼
阿新 • • 發佈:2017-07-05
all return 後繼節點 head 遍歷 dex blink span fin
在單鏈表當中,從已知節點出發,只能訪問該節點的後繼節點,卻無法訪問
該節點之前的節點,在單循環鏈表當中,雖然可以通過一個節點訪問表中所
有節點,但是要找到直接前驅卻要遍歷整個表,因此為了加快尋找某個節點
的前驅,可以在每個節點的結構體上添加一個直接訪問前驅的指針域來快速
定位前驅節點。下面是簡單的雙鏈表代碼,當然優勢還沒有體現出來,後面
在慢慢補充
#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;
}
雙向鏈表代碼