# include <cstdio>
# include <cstdlib>
#include <iostream>
using namespace std;
typedef struct Node{
int data;
struct Node * next;
Node():next(NULL){}
Node(int a,Node*nx=NULL):data(a),next(nx){}
}*pNode;
pNode init(int n){
pNode head = new Node;
pNode p=head;
for(int i=0;i<n;++i) {
p->next = new Node(i);
p=p->next;
}
return head;
}
void _p(pNode q) {
if(!q) return;
int i=1;
pNode p=q->next;
while(p) {
for(int j=0;j<i;++j) putchar('-');
printf("[%d]\n",p->data);
p=p->next;
++i;
}
}
pNode merge(pNode h,pNode h2)
{
if(!h->next) return h2;
if(!h2->next) return h;
pNode p=h->next,q=h2->next;
pNode res=p->data > q->data?h2:h;
pNode pre=NULL;
while(p && q) {
pre = p;
while(p && p->data<=q->data) pre=p,p=p->next;
if(pre == p && p->next) p = p->next;
if(!p) break;
pre->next=q;
pre=q;
while(q && q->data<p->data) pre=q,q=q->next;
if(q==pre &&q->next) q=q->next;
if(!q) break;
pre->next = p;
}
if(p) pre->next = p;
else if(q) pre->next = q;
return res;
}
int main(){
int a,b;
while(cin >> a >> b) {
pNode ph = init(a);
pNode ph2=init(b);
//_p(ph);
//_p(ph2);
pNode m=merge(ph,ph2);
_p(m);
}
return 0;
}
有序单链表排序[面试题目]
最新推荐文章于 2020-01-30 22:38:41 发布