| 
 | 
 
1鱼币 
以下是源代码,程序目的是  动态链表删除其中某一项,然后输出删除前后的动态链表 
在红色那行设置了断点,断点处的指针值和退出该子函数后的指针值为什么发生了变化,给出了我debug程序时的输入和子函数内外指针的数值, 
 
 
#include <stdio.h> 
#include <malloc.h> 
#include <stdlib.h> 
 
#define LEN sizeof(struct student)  // student结构的大小 
 
struct student *creat();            //创建链表    
void print(struct student *head);   //打印链表 
void del(struct student * ); //删除指定链表中指定学号的student结构体 
 
struct student 
{ 
      int num; 
      float score; 
      struct student *next; 
}; 
 
int n; //全局变量,用来记录存放了多少数据。 
 
void main() 
{ 
      struct student *stu; 
 
      stu = creat();//创建一个链表 
      print( stu );//打印链表 
          del(stu); 
          print(stu); 
 
      printf("\n\n"); 
      system("pause"); 
} 
 
struct student *creat() 
{ 
      struct student *head; 
      struct student *p1, *p2; 
          head = NULL;     
      n = 0; 
 
 
      p1 = (struct student *)malloc(LEN);   
          p2=p1; 
 
 
      printf("Please enter the num :"); 
      scanf("%d", &p1->num); 
      printf("Please enter the score :"); 
      scanf("%f", &p1->score); 
 
 
 
 
      while( 0 != p1->num ) 
      { 
 
            n++; 
            if( 1 == n ) 
            { 
                  head = p1;                  
            } 
            else 
            { 
                  p2->next = p1; 
            } 
 
            p2 = p1; 
 
 
            p1 = (struct student *)malloc(LEN); 
 
 
            printf("\nPlease enter the num :"); 
            scanf("%d", &p1->num); 
            printf("Please enter the score :"); 
            scanf("%f", &p1->score); 
 
 
 
      } 
 
      p2->next = NULL; 
 
 
      return head; 
} 
 
void print(struct student *head) 
{ 
      struct student *p; 
      printf("\nThere are %d records!\n\n", n); 
 
      p = head; 
      if( NULL != head ) 
      { 
            do 
            { 
                  printf("学号为 %d 的成绩是: %f\n", p->num, p->score); 
                  p = p->next; 
            }while( NULL != p ); 
      } 
} 
 
void del(struct student *stu) //删除指定链表中指定学号的student结构体 
{ 
        int num,i; 
        struct student *p1,*p2; 
        p1=p2=stu; 
        printf("input the student number you want to del:"); 
        scanf("%d",&num); 
        for(i=0;p1->next!=NULL;p1=p1->next,i++) 
        { 
                if(p1->num==num) 
                { 
                        if(i!=0) 
                                p2->next=p1->next; 
                        else 
                        { 
                                stu=p1->next; 
                                p1=p2=stu; 
                                i--; 
                        } 
                } 
                else 
                { 
                        p2=p1; 
                } 
 
        } 
 
}//插入断点 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 |   
 
 
最佳答案
查看完整内容 
DEL函数中 
 if(i!=0)
  p2->next=p1->next;  有逻辑问题,首先你删除num为1的时,i本来就是0,所以就转到else去了。所以就没删除掉。你删除num为2的应该不会有错了 
 
 
 
 
 
 
 |