1. 程式人生 > >雙向迴圈連結串列(帶頭結點)

雙向迴圈連結串列(帶頭結點)

//定義結構體

typedef struct data {

      int  data;

      struct data *pro;   //前驅

      struct data *next; //後繼

}DATA;

//建立雙向迴圈連結串列

DATA *creat () {


    DATA  *head, *node1, *node2;
    char choice;

//先建立一個空的雙向迴圈連結串列

    head = node1 = malloc(N);

    head->next = head;
    head->pro = head;

    printf ("\n PLease input the data:   \n");
    do {
    
        node2 = malloc(N);

        scanf ("%d“,node -> data);

        node2->next = head;
        head->pro = node2;
        node2->pro = node1;
        node1->next = node2;
        node1 = node2;
        
        printf ("\nDo you want to continue?(y/n) \n");
        getchar();
        scanf ("%c", &choice);
    
    }while (choice == 'y' || choice == 'Y');

    return head;

}

//插入
int insert (DATA *head) {

    char choice;
    DATA *node, *node_insert;

    node = head->next;

    printf ("\n insert: \n");
    do {
            node_insert = malloc(N);

            printf ("\nPlease input the data you want to insert:\n");
            scanf ("%d", &node_insert -> data);
            printf ("%d", node_insert -> data);
    
            while (node != head  && node_insert -> data  < node -> data) {
        
                node = node->next;
        
            }
    
            node_insert->pro = node->pro;
            node->pro->next = node_insert;
            node_insert->next = node;
            node->pro = node_insert;

            printf ("\nDo you  want to continue?(y/n)");
            getchar();
            scanf ("%c", &choice);
    
        }while (choice == 'y' || choice == 'Y');


    return 0;
}

//刪除  類比插入自行推理~

小編提示:不要忘記在建立在開始建立一個空的雙向迴圈連結串列,小編之前就忘記了,結果出現大大的bug,後來,請教了小編的老師,才知道的。之前在網上搜索的感覺好像看不懂,而且還有bug,給老師看得時候,老師說“你連單向的都不清楚,先用單向吧”,所以,網上的程式,你們懂得,小編就不多說了,但是,小編的一定時=是正確的哦。還有,就是在交換的時候,注意指標的指向,最好畫畫圖,搞清楚,不要繞暈啦,之前小編就暈呢。