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));
    if (head==NULL) 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;
    C=A;
    C->next=NULL;
    while(p!=NULL&&q!=NULL)
    {
        if(p->data<=q->data)
        {
            r=p;
            p=p->next;
            r->next=C->next;
            C->next=r;
        }else
        {
            r=q;
            q=q->next;
            r->next=C->next;
            C->next=r;
        }
    }
    while(p!=NULL)
    {
        r=p;
        p=p->next;
        r->next=C->next;
        C->next=r;
    }
    while(q!=NULL)
    {
        r=q;
        q=q->next;
        r->next=C->next;
        C->next=r;
    }
}
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:55 yyj 阅读(317) 评论(0)  编辑 收藏 引用

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