当前位置: 代码迷 >> C语言 >> 链表问题:(p1=p1->next;)和(p2=p1->next;p1=p2;)有区别么?
  详细解决方案

链表问题:(p1=p1->next;)和(p2=p1->next;p1=p2;)有区别么?

热度:405   发布时间:2008-04-21 22:01:19.0
链表问题:(p1=p1->next;)和(p2=p1->next;p1=p2;)有区别么?
下面是源代码,愿意帮忙的朋友主要看下main()部分就可以。我想不通为什么main()中的代码(2)换成代码(1),就错了呢?(当用代码(2)替换后,程序似乎执行到88行就终止了。)
最后请解释下(p=p->next;)和(p2=p1->next;p1=p2;)有什么区别啊?不就是多了一个指针变量p么。
#include "stdio.h"
#include "malloc.h"
#define null 0
#define len sizeof(struct student)
int n;
struct student
{
    long num;
    long score;
    struct student *next;
};
struct student *creat(void)
{   
    struct student *p1,*p2,*head;
    head=null;
    printf("please input the students' data:\n");
    p1=p2=(struct student *)malloc(len);
    //scanf("%ld %ld",&p1->num,&p1->score);
    n=0;
    while(scanf("%ld %ld",&p1->num,&p1->score)!=EOF&&p1->num!=0)
    {
        n++;
        if(n==1)head=p1;
        else
        {
            p2->next=p1;
            p2=p1;
        }
            p1=(struct student *)malloc(len);
            //scanf("%ld %ld",&p1->num,&p1->score);
    }   
    p2->next=null;
    return(head);
}
void print(struct student *head)
{
    struct student *p;
    p=head;
    while(p!=null)
    {
        printf("%ld %ld\n",p->num,p->score);
         p=p->next;
    }
   
   
}
struct student *insert(struct student *head,struct student *p)
{
    struct student *p1,*p2;
    p1=p2=head;
        if(head==null)head=p;
        else
        {
            while(p->num>p1->num&&p1->next!=null)
            {
                p2=p1;p1=p1->next;
            }
            if(p->num<=p1->num)
            {
                if(p1==head)
                {
                    head=p;p->next=p1;
                }
                else
                {
                    p2->next=p;p->next=p1;
                }
            }
            else
            {
                p1->next=p;p->next=null;
            }

        n++;
        
    }
   
    return(head);
}
   
   
main()
{
    struct student *a,*b,*p1,*p2;
    a=creat();
    print(a);
    b=creat();
    print(b);
    p1=a;
    /*(1)while(p1!=null)
    {
        b=insert(b,p1);
        p1=p1->next;
    }(1)*/
    /*(2)*/while(p1!=null)
    {
        p2=p1->next;
        b=insert(b,p1);
        p1=p2;
    }/*(2)*/
    printf("the %d data:\n",n);
    print(b);
   
}
搜索更多相关的解决方案: 链表  next  

----------------解决方案--------------------------------------------------------
真是很讨厌这种教材式的代码,又不是写得怎么样那才是个糟糕的问题

PS. p1的后继在函数内被改掉

[color=white]
----------------解决方案--------------------------------------------------------
  相关解决方案