鏈表合并,表合并

來源:互聯網
上載者:User

鏈表合并,表合并

設有兩個無頭結點的單鏈表,頭指標分別為ha,hb,鏈中有資料域data,鏈域next,兩鏈表的資料都按遞增序存放,現要求將hb表歸到ha表中,且歸併後ha仍遞增序,歸併中ha表中已有的資料若hb中也有,則hb中的資料不歸併到ha中,hb的鏈表在演算法中不允許破壞。


#include<stdio.h> /// no have dead node  ha and hb >>ha#include<stdlib.h>typedef int ElemType;typedef struct LNode{ElemType data;struct LNode *next;}LNode,*LinkList;LinkList CreateLink(int n)  /// 建立表{    LinkList h=(LinkList)malloc(sizeof(LNode)),q;    scanf("%d",&h->data);    h->next=NULL;    q=h;    for(int i=1;i<n;i++){        LinkList p=(LinkList)malloc(sizeof(LNode));        scanf("%d",&p->data);        p->next=NULL;        q->next=p;        q=p;    }    return h;  /// 返回頭指標}void print(LinkList h);LinkList MergeList(LinkList ha,LinkList hb){    LinkList p,hc,pc;    p=(LinkList)malloc(sizeof(LNode));    p->next=NULL;    hc=pc=p;    while(ha&&hb)    {        if(ha->data < hb->data){            p=(LinkList)malloc(sizeof(LNode));            p->next=NULL;            p->data=ha->data;            pc->next=p;pc=p;ha=ha->next;        }        else if(ha->data > hb->data){            p=(LinkList)malloc(sizeof(LNode));            p->next=NULL;            p->data=hb->data;            pc->next=p;pc=p;hb=hb->next;        }        else{            /**            p=(LinkList)malloc(sizeof(LNode));            p->next=NULL;            p->data=ha->data;            pc->next=p;            pc=p;            ha=ha->next;            */            hb=hb->next; /// ha中有hb的元素,hb直接指向下一結點        }    }    pc->next=ha?ha:hb;  ///  指向剩餘的鏈表    return hc->next;    /// 返回無頭結點的指標}void print(LinkList h){    while(h!=NULL){        printf("%d ",h->data);        h=h->next;    }    printf("\n");}int main(){    int n,m;    scanf("%d",&n);   ///ha    LinkList ha=CreateLink(n);    scanf("%d",&m);    ///hb    LinkList hb=CreateLink(m);    printf("\nBefore MergeList\n");    print(ha);    print(hb);    ha=MergeList(ha,hb);    printf("After MergeList\n");    print(ha);    print(hb);    return 0;}/**61 5 7 9 34  7550 4 5 5 76*/




實驗結果,hb插入ha中,並且hb不變,ha仍然遞增

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.