国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C > 正文

C語言中數據結構之鏈表歸并排序實例代碼

2020-01-26 14:07:28
字體:
來源:轉載
供稿:網友

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"); } 

運行結果

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 敖汉旗| 望城县| 万州区| 黑水县| 盖州市| 东城区| 石楼县| 万源市| 太康县| 辽源市| 许昌市| 贵港市| 江达县| 塔城市| 菏泽市| 东安县| 桃江县| 鹤岗市| 宝丰县| 崇左市| 蒙城县| 乌苏市| 平阴县| 阿克苏市| 青海省| 兰州市| 林甸县| 明溪县| 四川省| 静乐县| 石景山区| 伊宁市| 太康县| 鄂托克前旗| 永兴县| 云南省| 许昌市| 那坡县| 竹北市| 沂南县| 梅州市|