C語言進階-第19講:鏈表應用(鏈表的合併)

任務與代碼:

輸入一個整數m,表示A鏈表的長度,再輸入m個數作爲A鏈表中的m個數據元素,建立鏈表A,其頭指針爲heada。輸入一個整數n,表示B鏈表的長度,再輸入n個數表示B鏈表中的n個數據元素,建立鏈表B,其頭指針爲headb。輸入i、len、j,將要從單鏈表A中刪除自第i個元素起的共len個元素,然後將單鏈表A插入到單鏈表B的第j個元素之前。最後輸出操作後的鏈表B。

例如,輸入:

11
13 5 14 62 3 43 71 5 72 34 5 (11個數構成鏈表A)
15
5 20 3 53 7 81 5 42 6 8 4 6 9 10 23(15個數構成鏈表B )
1 3 5(從單鏈表A中刪除自第1個元素起的共3個元素,然後將單鏈表A插入到單鏈表B的第5個元素之前

輸出:

5 20 3 53 62 3 43 71 5 72 34 5 7 81 5 42 6 8 4 6 9 10 23

    #include<stdio.h>
    #include<malloc.h>

    struct node
    {
        int data;
        struct node *next;
    };

    struct node *creat(int m)
    {
        struct node *head,*p,*q;
        head=(struct node *)malloc(sizeof(struct node));
        q = head;
        while(m--)                   //建立m+1個結點的鏈表,頭結點的數據域存放的是隨機數
        {
             p=(struct node *)malloc(sizeof(struct node));
             scanf("%d",&p->data);
             q->next = p;
             q = p;
        }
        q->next = NULL;
        return head;
    }

    int main()
    {
        int i,len,j;
        int m,n;
        struct node *heada,*headb,*p,*q;
        //創建鏈表
        scanf("%d",&m);
        heada = creat(m);
        scanf("%d",&n);
        headb = creat(n);
        scanf("%d%d%d;",&i,&len,&j);
        //刪除結點
        p = q = heada;
        while(--i)                   //循環i-1次,p,q出現在待刪結點前的位置
        {
            p = p->next;
            q = q->next;
        }
        while(len--)                 //循環len次
        {
            q = q->next;             //q出現在最後一個待刪結點的位置
        }
        p->next = q->next;           //更改待刪的前一個結點的地址域使其指向最後一個待刪結點之後的結點地址
        while(q->next != NULL)
            q = q->next;
        //合併鏈表
        p=headb;
        while(--j)
            p = p->next;             //從頭結點遍歷到鏈表B需要更改地址域的結點
        q->next = p->next;           //更改待插'結點'的地址域
        p->next = heada->next;       //更改待插'結點'前一個結點的地址域
        q = headb->next;
        while(q != NULL)             //遍歷合併後的鏈表
        {
            printf("%d ",q->data);
            q = q->next;
        }
        return 0;
    }


分析過程:


Q&A:

Q:爲什麼多建建立m+1個結點的鏈表,頭結點的數據域存放的是無效的數據?

A:爲了不單獨考慮插入結點是首結點,刪除結點也有首結點的情況。


發佈了94 篇原創文章 · 獲贊 44 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章