双向链表

双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表


 

typedef struct node{

    struct node *pre;   //前驱指针

    int age;

    struct node *next;  //后驱指针

}Node; 

int main(int argc, const char * argv[]) {

    Node * phead = NULL;

    Node * ptail = NULL;

    

    for (int i = 0; i<5; i++) {

        

        Node * ptemp = (Node*)malloc(1*sizeof(Node));

        if (ptemp == NULL) {

            exit(EXIT_FAILURE);

        }

        

        printf("请输入年龄:");

        scanf("%d",&ptemp->age);

        

        if (phead==NULL){

            ptemp->pre = NULL;

            phead = ptemp;

            ptail = ptemp;          

        }else{            

            ptail->next = ptemp;    //先用尾指针连接上temp

            ptemp->pre = ptail;    //再用temp连接上尾指针

            ptail = ptemp;    //尾指针指向temp指针

            phead->pre = ptail;    //头指针指向尾指针,形成循环

            ptail->next = phead;    //尾指针指向头指针,形成循环

        }  

    }

    

    Node * ptemp = phead;

    while (ptemp != NULL) {

        printf("%d",ptemp->age);

        ptemp = ptemp->next;      

        if (ptemp==phead){

            break;

        }

    }

    return 0;

}

原文地址:https://www.cnblogs.com/huoran1120/p/5050977.html