动态链表联系总结
来源:互联网 发布:cms系统下载 编辑:程序博客网 时间:2024/06/09 14:40
以下是解题《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;
}
*/
- 动态链表联系总结
- c链表联系
- 联系第五天总结
- 动态交叉表总结
- 联系各种动态添加表格
- 心电导联系统总结
- angularjs1官方教程联系总结:
- 动态规划经典联系题----找零钱
- 浅谈动态规划,贪婪,回溯算法联系
- 关于单向动态链表的一些总结
- 【动态规划】【贪心】动态规划与贪心的联系
- 总结Java equals()和hashCode()的联系
- BP与CNN的联系总结
- 表、栈、队列联系
- 表、栈、队列联系
- 表、栈、队列联系
- 联系
- 联系
- 退色的爱
- 从printf说开去(一)
- 如何在tomcat上配置jruby on rails
- 控制ajax调用一次
- java开发要掌握的知识点
- 动态链表联系总结
- 从printf说开去(二)
- Eclipse(Myeclipse)中安装在线(离线)配置ADT插件
- 与NTFS文件系统相关的MBR和DBR的简但分析
- java i/o各种封装类及例子
- Google Maps地图投影全解析
- 自定义控件自动出现在工具栏
- 冒泡排序,快速排序,插入排序(JS版)
- 使用谷歌浏览器调试网页和脚本