C語言中怎么實現鏈表歸并排序,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
創新互聯主營拉薩網站建設的網絡公司,主營網站建設方案,app軟件開發,拉薩h5成都小程序開發搭建,拉薩網站營銷推廣歡迎拉薩等地區企業咨詢
C語言中數據結構之鏈表歸并排序實例代碼
問題
設有兩個無頭結點的單鏈表,頭指針分別為ha,hb,鏈中有數據域data,鏈域next,兩鏈表的數據都按遞增排序存放,現要求將hb表歸到ha表中,且歸并后ha仍遞增序,歸并中ha表中已有的數據若hb中也有,則hb中的數據不歸并到ha中,hb的鏈表在算法中不允許破壞。
源程序
#include <stdio.h> #include<stdlib.h> #define N1 6 /*鏈表La的長度*/ #define N2 6 /*鏈表Lb的長度*/ struct listnode { int data; struct listnode *next; }; void createlist(struct listnode * *,int); void listinsert(struct listnode * *,struct listnode * *); void readlist(struct listnode *); int main() { struct listnode *ha=NULL,*hb=NULL; printf("請按照升序序列輸入以下數字以建立鏈表La\n"); printf("Please Input %d numbers:",N1); createlist(&ha,N1); printf("請按照升序序列輸入以下數字以建立鏈表Lb\n"); printf("Please Input %d numbers:",N2); createlist(&hb,N2); listinsert(&ha,&hb); readlist(ha); printf("\n"); } void createlist(struct listnode * *p,int n) { /*尾插法建立鏈表*/ struct listnode *t,*q; int i; t=(struct listnode *)malloc(sizeof(struct listnode)); scanf("%d",&t->data); *p=t; q=t; for(i=n-1;i>0;i--) { t=(struct listnode *)malloc(sizeof(struct listnode)); scanf("%d",&t->data); q->next=t; q=t; } q->next=NULL; } void listinsert(struct listnode * *a,struct listnode * *b) { /*將兩個鏈表按遞增序列排序*/ struct listnode *pa,*pb,*other,*la,*pre; la=(struct listnode *)malloc(sizeof(struct listnode)); la->next=*a; pa=*a; pb=*b; pre=la; while(pa&&pb) { if(pa->data<pb->data) { pre=pre->next; pa=pa->next; } else if (pa->data>pb->data) { other=(struct listnode *)malloc(sizeof(struct listnode)); other->data=pb->data; other->next=pa; pre->next=other; pre=other; pb=pb->next; } else { pre=pre->next; pa=pa->next; pb=pb->next; } } if(!pa) { while(pb) { other=(struct listnode *)malloc(sizeof(struct listnode)); other->data=pb->data; pre->next=other; pre=pre->next; pb=pb->next; } pre->next=NULL; } *a=la->next; free(la); } void readlist(struct listnode *p) { /*遍歷鏈表并輸出最終結果*/ struct listnode *q; q=p; printf("鏈表的排序結果為:\n"); while(q!=NULL) { printf("%3d",q->data); q=q->next; } printf("\n"); }
運行結果
關于C語言中怎么實現鏈表歸并排序問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創新互聯行業資訊頻道了解更多相關知識。
文章名稱:C語言中怎么實現鏈表歸并排序
網址分享:http://m.newbst.com/article2/gdsoic.html
成都網站建設公司_創新互聯,為您提供云服務器、網站收錄、定制網站、網站建設、微信小程序、營銷型網站建設
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯