#include
using std::cin;
using std::cout;
using std::endl;
struct student
{
int num;
double score;
struct student *next;
};
int n;
struct student *creat();
struct student *deleate(struct student *p,struct student *q);
void output(struct student *);
int main()
{
struct student *x,*y,*z;
cout<<"please input the first set\n";
x=creat();
cout<<"please input the second set\n";
y=creat();
cout<<"the first set is:\n" ;
output(x);
cout<<"the second set is:\n";
output(y);
z=deleate(x,y);
cout<<"-----deleate-----\n";
output(z);
}
void output(struct student *h)
{
struct student *z;
z=h->next;
while(z!=0)
{
cout<num<<"\t"< score< z=z->next;
}
}
struct student *creat()
{
student *head,*p1,*p2;
n=0;
head=new(student); // The empty head node.
p1=new(student);
p2=p1;
cout<<"please input student's xuehao and chengji:";
cin>>p1->num>>p1->score;
while(p1->num!=0)
{
n++;
if(n==1)
head->next=p1;
else
p2->next=p1;
p2=p1;
p1=new(student);
cout<<"please input student's xuehao and chengji:";
cin>>p1->num>>p1->score;
}
delete(p1);
p2->next=0;
return head;
}
/* Return the target's next node pointor */
struct student *del_one_node(struct student *head, struct student *target)
{
struct student *p, *q;
q = head;
p = head->next; //p point to the firt valid node.
while (p && p != target) {
q = p; // save the p to q, so q point to the pre one node.
p = p->next;
}
if (!p) {
cout << "No such node .." << endl;
return NULL;
}
q->next = p->next;
cout << "delete one node: " << p->num << "\t" << p->score << endl;
delete(p);
return (q->next);
}
struct student *deleate(student *p,student *q )
{
student *p1,*p2;
p2 = q->next;
while (p2)
{
p1 = p->next; // p1 should point to the head everytime;
while (p1)
{
if (p1->num == p2->num)
p1 = del_one_node(p, p1);
else
p1 = p1->next;
}
p2 = p2->next;
}
return p;
}
在机器上测试OK。
与你现有实现不同的是:1. 使用了带有头节点的链表, 这样容易操作。2. 将删除的操作分为两个过程, 实现一辅助的函数每次删除一个节点, 这样程序更清晰。