鱼C论坛

 找回密码
 立即注册
查看: 2828|回复: 2

继续求教 谭浩强C程序设计11.10

[复制链接]
发表于 2011-3-27 01:31:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
输入两个链表a和b,要求将a中num与b中相同的结点删去。输入输出函数都测试过了,没有问题。应该是del函数的问题,每次运行都无法终止。谁能帮我看一下是为什么吗?
#include <stdio.h>
#include <malloc.h>
#define LEN sizeof(struct student)
struct student
{
        int num;
        int score;
        struct student *next;
};
int n;

struct student *creat()//创建链表
{
        struct student *head;
        struct student *p1,*p2;
        n=0;
        p1=p2=(struct student *)malloc(LEN);
        scanf("%d,%d",&p1->num,&p1->score);
        head=NULL;
        while(p1->num!=0)
        {
                n++;
                if(n==1) head=p1;
                else p2->next=p1;
                p2=p1;
                p1=(struct student *)malloc(LEN);
                scanf("%d,%d",&p1->num,&p1->score);
        }
        p2->next=NULL;
        return head;
}

void print(struct student *head)//输出函数
{
        struct student *p;
        p=head;
        if(head!=NULL)
        {
                while(p!=NULL)
                {
                        printf("%-6d%5d\n",p->num,p->score);
                        p=p->next;
                }
        }
}

struct student *del(struct student *a,struct student *b)
{
        struct student *p1,*p2,*p3;
        p1=a;
        p2=a;
        p3=b;
        while(p3->num!=0)
        {
                while(p1->next!=NULL && p3->num!=p1->num)
                {
                        p1=p1->next;
                        p2=p1;
                }
                if(p3->num==p1->num)//若找到p3->num,则不指向b链表的下一地址,在删节过的a链表中再寻找一次
                {
                        if(p1==a) a=p1->next;//若p1指向的是首地址,则把第二个结点地址赋予a
                        else p2->next=p1->next;//否则将下一结点地址赋予前一结点地址
                }
                else p3=p3->next;//若未找到P3->num则指向b链表的下一地址
                p1=a;
                p2=a;
        }
        return a;
}

void main()
{
        struct student *a,*b;
        printf("input LL a here:\n");
        a=creat();
        printf("input LL b here:\n");
        b=creat();
        printf("LL a:\n");
        print(a);
        printf("LL b:\n");
        print(b);
        a=del(a,b);
        printf("the deleted LL a:\n");
        print(a);
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
发表于 2011-3-27 02:21:51 | 显示全部楼层
明天的视频会讲解~
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
发表于 2015-12-11 12:01:28 | 显示全部楼层
:shock::shock::ton:
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-6 00:01

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表