有序单链表排序[面试题目]

来源:互联网 发布:合肥百度seo教程 编辑:程序博客网 时间:2024/05/22 12:08
# 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;}


原创粉丝点击