C語言中怎么實現(xiàn)鏈表歸并排序

C語言中怎么實現(xiàn)鏈表歸并排序,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

創(chuàng)新互聯(lián)主營拉薩網(wǎng)站建設的網(wǎng)絡公司,主營網(wǎng)站建設方案,app軟件開發(fā),拉薩h5成都小程序開發(fā)搭建,拉薩網(wǎng)站營銷推廣歡迎拉薩等地區(qū)企業(yè)咨詢

C語言中數(shù)據(jù)結構之鏈表歸并排序實例代碼

問題

       設有兩個無頭結點的單鏈表,頭指針分別為ha,hb,鏈中有數(shù)據(jù)域data,鏈域next,兩鏈表的數(shù)據(jù)都按遞增排序存放,現(xiàn)要求將hb表歸到ha表中,且歸并后ha仍遞增序,歸并中ha表中已有的數(shù)據(jù)若hb中也有,則hb中的數(shù)據(jù)不歸并到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("請按照升序序列輸入以下數(shù)字以建立鏈表La\n"); 
 printf("Please Input %d numbers:",N1); 
 createlist(&ha,N1); 
 printf("請按照升序序列輸入以下數(shù)字以建立鏈表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語言中怎么實現(xiàn)鏈表歸并排序

關于C語言中怎么實現(xiàn)鏈表歸并排序問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關知識。

文章名稱:C語言中怎么實現(xiàn)鏈表歸并排序
網(wǎng)址分享:http://muchs.cn/article2/gdsoic.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供云服務器、網(wǎng)站收錄定制網(wǎng)站網(wǎng)站建設、微信小程序、營銷型網(wǎng)站建設

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站