posts - 0,comments - 0,trackbacks - 0
升序链表的合并实现:
#include<iostream>
using namespace std;
typedef struct LNode
{
    int data;
    struct LNode *next;
}LNode;
//创建有头结点的链表结构
struct LNode *creat(LNode *head)
{
    struct LNode*p1,*p2;
    p1=(LNode*)malloc(sizeof(LNode));
    head=p1;
    while(p1->data!=0)
    {
        p2=p1;
        p1=(LNode*)malloc(sizeof(LNode));
        cin>>p1->data;
        p2->next=p1;
    }
    p2->next=NULL;
    return head;
}
//打印链表
void print(struct LNode *head)
{
    struct LNode *temp;
    temp=head->next;
    while(temp!=NULL)
    {
        cout<<temp->data<<"  ";
        temp=temp->next;
    }
    cout<<endl;
}

//合并两个链表
void merge(LNode *&A,LNode *&B,LNode *&C)
{
    LNode *p=A->next;
    LNode *q=B->next;
    LNode *r=A;
    C=r;
    while(p!=NULL&&q!=NULL)
    {
        if(p->data<=q->data)
        {
            r->next=p;
            p=p->next;
            r=r->next;
        }else
        {
            r->next=q;
            q=q->next;
            r=r->next;
        }
    }
    r->next=NULL;
    if(p!=NULL) r->next=p;
    if(q!=NULL) r->next=q;
}
int main()
{
    LNode *a=NULL;
    cout<<"请输入有序链表a(以零结束):";
    a=creat(a);
    print(a);
    LNode *b=NULL;
    cout<<"请输入有序链表b(以零结束):";
    b=creat(b);
    print(b);

    LNode *c=NULL;
    merge(a,b,c);
    print(c);
    

    return 0;
}
posted on 2012-08-21 15:37 yyj 阅读(106) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航:   博客园   博客园最新博文   博问   管理