注册 登录
编程论坛 数据结构与算法

两链表求交集

studythec 发布于 2010-04-11 19:19, 1653 次点击
题目是:建立两个链表,A,B找交集,放入C中
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#define NULL 0                                 //宏定义NULL为0
#define SIZ sizeof(struct stu)                 //宏定义 SIZ为sizeof(struct stu)
struct stu                                      //结构体
{
    int num;
    stu *next;
};                                                     
void main()
{
    stu *Ha=NULL; stu *Hb=NULL; stu *Hc=NULL; //定义头指针
    stu *r,*s;
    struct stu *p,*q;                                  //定义指针p,q
    int x;
    cout<<"in put A:"<<endl;                      //建立单链表A
    cin>>x;
    r=Ha;
    for(;x;cin>>x)                              
    {                       
        s=(stu*) malloc(SIZ);
        s->num=x;
        if(Ha==NULL)
            Ha=s;
        else
            r->next=s;
        r=s;
    }                           
    if(r!=NULL)
        r->next=NULL;
    r=Ha;                                     //输出单链表A
    while(r!=NULL)
    {
        cout<<r->num<<" ";
        r=r->next;
    }
     cout<<endl;
    cout<<"in put B:"<<endl;                      //建立单链表B
    cin>>x;
    r=Hb;
    for(;x;cin>>x)
    {
        s=(stu*)malloc(SIZ);
        s->num=x;
        if(Hb==NULL)                     
            Hb=s;
        else
            r->next=s;
        r=s;
    }
    if(r!=NULL)
        r->next=NULL;
    r=Hb;
    while(r!=NULL)                            //输出单项链表B
    {
        cout<<r->num<<" ";
        r=r->next;
    }
     cout<<endl;
     p=Ha;q=Hb;                               //建立链表C
     r=Hc;
     for(;p&&q;p=p->next,q=q->next)
         if(p->num=q->num)
         {
             s=(stu*) malloc(SIZ);
             s->num=p->num;
             if(Hc==NULL)
             {
                 Hc=s;
                 r=Hc;
             }
             else
             {
                 r->next=s;
                 r=s;
             }
         }
    if(r!=NULL)
        r->next=NULL;
    r=Hc;                                   //输出链表C
    while(r!=NULL)
    {
        cout<<r->num<<" ";
        r=r->next;
    }
    cout<<endl;
}
5 回复
#2
asdjc2010-04-11 19:26
你要问什么?
#3
sjz_zdf2010-04-12 14:09
展示这个这个程序是否正确?应该没错吧。
#4
studythec2010-04-12 15:55
错了啊,出不了结果
#5
画圈成句点2010-04-12 18:54
搞不懂
#6
韩明海2010-04-14 11:39
typedef struct student
{
    int num;
    struct student *next;
}stu;
以后就用stu定义结构体 变量就行了
再去检查一下你的if语句
1