#include
#include
#include
#define NULL 0
#define LEN sizeof(struct Student)
using namespace std;
typedef struct Student
{
int length;
int num;
struct Student *next;
}Student;
typedef Student *Linklist; //头指针
void Error(char *s) //错误指示
{
std::cout << s << endl;
exit(1);
}
Student *creat(void) //创建链表
{
Student *head;
Student *p, *q;
intn = 0;
q = (Student*)malloc(LEN);
p = q;
cout << "请输入元素:" << endl;
cin >> p->num;
head = NULL;
while (p->num != 0)
{
n = n + 1;
if (n == 1)
{
head = p;
head->length = 1;
}
else
{
q->next = p;
q = p;
p = (Student*)malloc(LEN);
cin >> p->num;
head->length++;
}
}
q->next = NULL;
return head;
cout << "链表创建成功!" << endl;
}
void Insertlist(Linklist &L, int i, int stu)
//向链表中第i个位置插入元素stu
{
Student *p =L; //将指针头传给指针p
int j = 1;
while (p && (j < i - 1)) //向后扫描查找
{
p = p->next;
j++;
}
if (!p || (j < i - 1)) //输入参数不对,给出错误提示,并跳出
Error("Postion Eeeor!");
else
{
Student *s = new Student;
s->num =stu;
s->next = p->next;
p->next = s;
p->length++;
}
}
void Deletelist(Linklist &L, int i, int stu)
//删除链表中第i个元素,并用stu返回
{
Student *p = L; //将指针头传给指针p
int j = 1;
while (p && (j < i - 1))
{
p = p->next;
j++;
}
if (!p || (j < i - 1))
Error("Postion Eeeor!"); // 输入参数不对,给出错误提示,并跳出
else
{
Student *q = p->next;
stu= p->num;
p->next = q->next;
delete q;
p->length--;
}
}
void Traverlist(Linklist L) //将链表依次数据输出
{
Student *p = L;
while (p)
{
cout << p->num << " ";
p = p->next;
}
cout << endl;
}
Student *Location(Linklist &L, int stu) //查找函数,查找元素stu所在的位置
{
int i = 2;
Student *p = L->next;
if (ilength-1)
{
while (p->next != NULL && (p->num != stu))
{
p = p->next;
i++;
}
cout << "该元素所在的位置是:" << i << endl;
}
else
cout << "该元素不存在!" << endl;
return p;
}
int main()
{
Student *head, *p;
int stu,n, number;
while (1)
{
cout << " 1、创建信息表" << endl;
cout << " 2、插入元素" << endl;
cout << " 3、查询元素" << endl;
cout << " 4、删除元素" << endl;
cout << " 5、退出程序" << endl;
cout << " 请选择所要执行的操作:";
cin >> n;
switch (n)
{
case 1:
head=creat();
Traverlist(head);
break;
case 2:
cout << "请输入插入的位置和元素:";
cin >> number;
cin >> stu;
while (stu != 0)
{
Insertlist(head, number, stu);
Traverlist(head);
cout << "请输入插入的位置和元素:";
cin >> number;
cin >> stu;
}
break;
case 3:
cout << "请输入查找的元素:";
cin >> stu;
while (stu != 0)
{
p = Location(head, stu);
cout << "请输入查找的元素:";
cin >> stu;
}
break;
case 4:
cout << "请输入要删除的位置 :";
cin >> number;
while (number!=0)
{
Deletelist(head, number, stu);
Traverlist(head);
cout << "请输入要删除的位置 :";
cin >> number;
}
break;//程序结束
case 5:
exit(1);
break;//程序结束
default:
cout << "输入错误,请重新输入!!!!!" << endl;
continue;
}
}
return 0;
}