| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
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); 
} |   
 
 
 
 |