链表的简单实现

来源:互联网 发布:php 中class exists 编辑:程序博客网 时间:2024/06/03 21:52
#include<iostream>
using namespace std;
struct Student
{
long long num;
float score;
struct Student *next;
};
int n;//全局变量
Student *head;
Student *creat();
void print(Student *);
Student *insert(Student *, Student *);
Student *del(Student *, long long );
int main()
{
Student *stu;
long long delnum;
cout << "输入数据学号和成绩" << endl;
head = creat();
print(head);//输出全部的结点
cout << "请输入要删除的学生号码,输入0,停止循环" << endl;
cin >> delnum;
while (delnum != 0)
{
head = del(head, delnum);
print(head);
cout << "请输入要删除的学生号码,输入0,停止循环" << endl;
cin >> delnum;


}
cout << "输入要插入的数据,输入0停止" << endl;
stu = new Student;
cin >> stu->num >> stu->score;
while (stu->next!=0)
{
head = insert(head, stu);
print(head);
cout << "输入要插入的数据,输入0停止" << endl;
stu = new Student;
cin >> stu->num >> stu->score;
}
system("pause");
return 0;
}
Student *creat()
{
Student * p1, *p2;
n = 0;
p1 =p2= new Student;
cin >> p1->num;
cin >> p1->score;
head = NULL;
while (p1->num != 0)
{
n++;
if (n==1)   head = p1;
else  p2->next = p1;
p2 = p1;
p1 = new Student;
cin >> p1->num;
cin >>p1->score;
}
p2->next = NULL;
return (head);
}
void print(Student *head)
{
Student *p;
p = head;
if (head!=NULL)
do
{
cout << p->num << " " << p->score << endl;
p = p->next;
} while (p != NULL);
}
Student *del(Student *head, long long num)
{
Student *p1, *p2;
if (head == NULL)
{
cout << "空表" << endl;//空表
return head;
}
p1 = head;
p2 = p1; 
while (num != p1->num&&p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if (num == p1->num)//find it
{
if (p1 == head)head = p1->next;
else p2->next = p1->next;
cout << "delete  " << num << endl;
n = n + 1;
}
else cout << "无法找到" << num << endl;
return head;
}


Student *insert(Student *head, Student *stud)
{
Student *p0, *p1, *p2;
p1 = head; p0 = stud; p2 = p1;//p1 指向第一个结点,p0指向要插入节点
if (head == NULL)//原来的表是空的
{
head = p0;
p0->next = NULL;
}
else
{
while ((p0->num) > (p1->num) && (p1->next != NULL))
{
p2 = p1;
p1 = p1->next;
}
if (p0->num <= p1->num)
{
if (head == p1) head = p0;
else p2->next = p1;
}
else
{
p1->next = p0;
p0->next = NULL;
}

}
n = n + 1;
return head;
}
原创粉丝点击