以下是解題《C++程序設計題解與上機指導》chapter 7.10的總結
#include<iostream>
using namespace std;
#define NULL 0
struct student
{ long num;
float score;
student *next;
};
int n=0;
student *create(void);
void print(student *);
student *del(student *,long);
student *insert(student *, student *);
void main()
{ student *head/*, stu */;
long del_num;
cout<<"input records:"<<endl;
head = create();
print(head);
do
{
cout<<endl<<"input the deleted number:";
cin>>del_num;
head=del(head, del_num);
print(head);
}while(del_num != 0);
}
student *create(void)
{ student *head=NULL;
student *p1, *p2;
p1=new student;
cin>>p1->num>>p1->score;
while(p1->num != 0)
{ n++;
if(!head)
head=p1;
else
p2->next=p1;
p2=p1;
p1 = new student;
cin>>p1->num>>p1->score;
}
p2->next=NULL; //next是指針,不是數值
return head;
}
void print(student * head)
{ student *p=head;
cout<<"Now, These "<<n<<" records are: "<<endl;
while(p != NULL)
{ cout<<"Num:"<<p->num<<" ";
cout<<"Score:"<<p->score<<endl;
p=p->next;
}
}
student *del(student * head,long num)
{ student *p1, *p2;
if(NULL == head)
{ cout<<"List is null!"<<endl; //適當輸出相應提示信息
return head;
}
p1=head;
while((p1->num != num) && (NULL != p1->next))
/*不能用“while((p1->num != num) && (NULL != p1))”代替上面的語句
當找不到的時候,while 會因爲 p1 == NULL 結束,
然後下面緊接着的語句是 if(p1->num == num),在此句中,
因爲 p1 是 NULL,所以 p1->num 是非法訪問。 所以使用一個指針的成員務必保證它不是空的
*/
{ p2=p1;
p1=p1->next;
}
if(p1->num == num)
{ if(head == p1)
head=p1->next;
else
p2->next=p1->next;
n--;
cout<<num<<" has been deleted!";
}
else
cout<<num<<" has not found!";
cout<<endl;
return head;
}
/*
student *del(student * head,long num)
{ student *p1, *p2;
if(head == NULL)
return head;
p1=p2=head;
if(p1->num == num)
{//注意欲返回的值是head不是p2,由於動態鏈表的每個節點是無名的,頭指針相當於一條鏈表的入口
//p2=p1->next;
head=p1->next;
n--;
return head;
}
p1=p1->next;
while(p1 != NULL)
{ if(p1->num == num)
{ p2->next = p1->next;
n--;
return head;
}
p2=p1;
p1=p1->next;
}
return head;
}
*/