双向链表的创建
创建一个双项链表,先从头到尾打印,然后从尾到头打印。
程序如下:
#include<stdio.h>
#include<stdlib.h>
struct NODE{
struct NODE *fwd; //定义前驱指针
struct NODE *bwd; //定义后续指针
int value;
};
int main(){
int num = -1;
struct NODE *head,*tail,*temp,*ptr;
head = tail = temp = ptr = NULL;
printf("please input the number of the doulb_list ends with 0:/n");
scanf("%d ",&num);
while(num!=0){
temp = (struct NODE *)malloc(sizeof(struct NODE)); //申请空间
if(head == NULL){
temp->value = num; //如果为头结点,那么head和tail的fwd和bwd
head = tail = temp; //都指向头结点
head->fwd = head->bwd = head;
tail->bwd = tail->fwd = head;
}
else{
temp->value = num;
tail->bwd = temp; //如果不是头结点,那么tail的后续指向temp
temp->fwd = tail; //temp的前驱指向tail
temp->bwd = head; //temp的后续指向头结点
tail = temp; //最后tail指向temp,也就是现在的尾部
head->fwd = tail; //最后head的前驱指向tail
}
scanf("%d ",&num);
}
printf("the members in this list is:/n");
for(ptr=head;ptr!=tail;ptr=ptr->bwd) //从head到taill打印
printf("%d ",ptr->value);
printf("%d/n",tail->value);
printf("the member in this list is:/n");
for(ptr=tail;ptr!=head;ptr=ptr->fwd) //从tail到head打印
printf("%d ",ptr->value);
printf("%d/n",head->value);
return 0;
}