日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

两个无序单链表,排序后合并成一个有序链表

發布時間:2023/11/27 生活经验 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 两个无序单链表,排序后合并成一个有序链表 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

兩個無序單鏈表,排序后合并成一個有序鏈表

?

算法思想:用冒泡法,對鏈表1和2進行排序,對排序后的兩個鏈表,從小到大進行循環,裝入鏈表3中。

#include<stdio.h>
#include<stdlib.h>struct stud/*定義鏈表*/
{
int data;
struct stud *next;
};void pai_xue(struct stud *head1,struct stud *head2,int count1,int count2)/*冒泡排序法*/
{int i,j,temp=0;
struct stud *p;for(i=0;i<count1-1;++i)for(p=head1->next;p->next!=NULL;p=p->next)/*對鏈表1進行排序*/{if(p->data>p->next->data){temp=p->data;p->data=p->next->data;p->next->data=temp;}}for(i=0;i<count2-1;++i)for(p=head2->next;p->next!=NULL;p=p->next)/*對鏈表2進行排序*/{if(p->data>p->next->data){temp=p->data;p->data=p->next->data;p->next->data=temp;}}printf("\n鏈表1排完序后\n");/*輸出鏈表1和2*/p=head1->next;while(p){printf("%d",p->data);p=p->next;}printf("\n");printf("\n鏈表2排完序后\n");p=head2->next;while(p){printf("%d",p->data);p=p->next;}printf("\n");}void main()
{struct stud *head1,*head2,*p,*q,*head3;
int count1=1,count2=1;head3=(struct stud *)malloc(sizeof(struct stud *));/*定義鏈表頭結點,并分配空間*/
head3->next=NULL;head1=(struct stud *)malloc(sizeof(struct stud *));
head2=(struct stud *)malloc(sizeof(struct stud *));
p=(struct stud *)malloc(sizeof(struct stud *));
q=(struct stud *)malloc(sizeof(struct stud *));head1->next=NULL;
head2->next=NULL;printf("輸入一個數據以999結束\n");
scanf("%d",&p->data);while(p->data!=999)/*鏈表1輸入數據*/
{count1++;
p->next=head1->next;
head1->next=p;
printf("輸入一個數據以999結束\n");
p=(struct stud *)malloc(sizeof(struct stud *));
scanf("%d",&p->data);}printf("現在開始給第二個鏈表輸入數據\n");printf("輸入一個數據以999結束\n");
scanf("%d",&q->data);while(q->data!=999)/*鏈表2輸入數據*/
{count2++;
q->next=head2->next;
head2->next=q;
printf("輸入一個數據以999結束\n");
q=(struct stud *)malloc(sizeof(struct stud *));
scanf("%d",&q->data);}pai_xue(head1,head2,count1,count2);head1=head1->next;
head2=head2->next;
while(head1!=NULL&&head2!=NULL)/*將排序好的鏈表1和2 的數據導入鏈表3*/
{if(head1->data<=head2->data){p=head1->next;head1->next=head3->next;head3->next=head1;head1=p;}else{q=head2->next;head2->next=head3->next;head3->next=head2;head2=q;}
}if(head1!=NULL)/*如果有鏈表1或2的數據不為空,將剩下的數據導入鏈表3中*/
{p=head1;while(p!=NULL){q=p->next;p->next=head3->next;head3->next=p;p=q;}}
if(head2!=NULL)
{q=head2;while(q!=NULL){p=q->next;q->next=head3->next;head3->next=q;q=p;}}q=head3->next;/*將鏈表倒置,原來是由大到小,倒置成由小到大*/
head3->next=NULL;
while(q!=NULL)
{p=q->next;q->next=head3->next;head3->next=q;q=p;
}printf("兩個鏈表合并后由小到大為\n");p=head3->next;
while(p)
{
printf("%d",p->data);
p=p->next;
}
}

總結

以上是生活随笔為你收集整理的两个无序单链表,排序后合并成一个有序链表的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。