求有序链表合并后的中位数

来源:互联网 发布:sqlserver 不允许更改 编辑:程序博客网 时间:2024/05/30 05:21

序号输入输出1

51 3 5 7 92 3 4 5 6
4
2
6-100 -10 1 1 1 1-50 0 2 3 4 5
1
3
31 2 34 5 6
3
4
34 5 61 2 3
3
5
121
1

已知有两个等长的非降序序列S1, S2, 设计函数求S1与S2并集的中位数。有序序列A0, A1…AN-1的中位数指A(N-1)/2的值,即第[(N+1)/2]个数(A0为第1个数)。

输入格式说明:

输入分3行。第1行给出序列的公共长度N(0<N<=100000),随后每行输入一个序列的信息,即N个非降序排列的整数。数字用空格间隔。

输出格式说明:

在一行中输出两个输入序列的并集序列的中位数。

样例输入与输出:

#include<stdio.h>#include<stdlib.h>#define LEN sizeof(struct node)struct node{int num;struct node *next;};struct node *creat(int n){struct node *p1,*p2,*head;int i=0;head=NULL;while(n--){p1=(struct node*)malloc(LEN);if(i++==0)head=p1;elsep2->next=p1;p2=p1;scanf("%d",&p1->num);}p2->next=NULL;return head;}struct node *combine(struct node *p1,struct node *p2){struct node *p,*q,*head;head=NULL;int i=0;while(p1!=NULL && p2!=NULL){while( p1->num >= p2->num ){p=(struct node*)malloc(LEN);p->num=p2->num;if(i++==0)head=p;elseq->next=p;q=p;p2=p2->next;if(p2==NULL)break;}if(p1==NULL || p2==NULL)break;while( p1->num < p2->num){p=(struct node*)malloc(LEN);p->num=p1->num;if(i++==0)head=p;elseq->next=p;q=p;p1=p1->next;if(p1==NULL)break;}}while(p1!=NULL){p=(struct node*)malloc(LEN);p->num=p1->num;if(i++==0)head=p;elseq->next=p;q=p;p1=p1->next;}while(p2!=NULL){p=(struct node*)malloc(LEN);p->num=p2->num;if(i++==0)head=p;elseq->next=p;q=p;p2=p2->next;}if(i)    p->next=NULL;return head;}int find(node *p,int k){     int i=1;      while(p!=NULL && i<k)      {          p=p->next;          i++;      }      if(i==k)          return p->num; }int main(){struct node *p1,*p2,*p;int n,a,b;scanf("%d",&n);p1=creat(n);p2=creat(n);p=combine(p2,p1);a=find(p,n);b=find(p,n+1);printf("%d\n",(a+b)/2);return 0;}

这三道有关有序链表的题目代码大同小异,只要完成其中一个以后稍加修改就可以完成其他。

0 0
原创粉丝点击