#include <iostream>
using namespace std;
struct note
{
int a;
note *next;
};
//全局变量
note *head = new note;
note *tail = new note;
int n;
void creatlist()
{
cout << "请输入所建链表的数量:";
cin >> n;
head = NULL;
tail = NULL;
int num;
note *temp =new note;
if (temp == NULL)
{
cout << " 申请失败";
}
cout << "input num = ";
cin >> num;
temp->a = num;
temp->next = NULL;
if (head == NULL)
{
head = temp;
tail = temp;
}
for (int i = 0; i < n-1; i ++)
{
temp = new note;
if (temp == NULL)
{
cout << " 申请失败";
}
cout << "input num = ";
cin >> num;
temp->a = num;
temp->next = NULL;
tail->next = temp;
tail = temp;
}
}
void outputList()
{
note *temp = head;
while (temp!=NULL)
{
cout << temp->a<< "\t";
temp = temp->next;
}
cout << endl;
}
void deleteLIst()
{
cout << "请输入你要删除的数字:";
cin >> n;
note *temp = head;
note *fore = NULL;
while(temp!=NULL && temp->a != n)
{
fore = temp;
temp = temp->next ;
}
if (fore == NULL)
{
head = temp->next ;
delete temp;
}
else if (temp == NULL)
{
delete temp;
}
else if (temp->a==n)
{
fore->next = temp->next;
delete temp;
}
else
{
cout << "没有找到;";
}
outputList();
cout << "已经删除;"<< endl;
}
void insert( )
{
cout << "请输入你要插入的数字:";
cin >> n;
note *temp = head;
note *fore = NULL;
note *cur = new note;
while(temp!=NULL && temp->a < n )
{
fore = temp;
temp = temp->next ;
}
if (fore == NULL)
{
cur->a = n;
cur->next = temp;
head = cur;
}
else if (temp == NULL)
{
temp->next = cur;
cur->a = n;
cur->next = NULL;
}
else
{
cur->a = n;
fore->next = cur;
cur->next = temp;
}
cout << "插入成功:";
outputList();
}
void findLIst()
{
cout << "请输入你要查找的数字:";
cin >> n;
note *temp = head;
note *fore = NULL;
while(temp!=NULL && temp->a != n)
{
fore = temp;
temp = temp->next ;
}
if (temp->a == n)
{
cout << n << "在链表中"<< endl;
}
else
{
cout << n << "不在链表中"<< endl;
}
}
void miue();
void select();
int main()
{
miue();
}
void select()
{
int selet ;
while(1)
{
cout << "请输入你要进行的选择:";
cin >> selet;
switch(selet)
{
case 1:creatlist();break;
case 2:outputList();break;
case 3:deleteLIst();break;
case 4:insert( );break;
case 5:findLIst();break;
}
miue();
}
}
void miue()
{
cout << "***********链表************" << endl;
cout << "1--------------创建链表" << endl;
cout << "2--------------显示链表" << endl;
cout << "3--------------删除数字" << endl;
cout << "4--------------插入数字" << endl;
cout << "5--------------寻找数字" << endl;
cout << "***************************" << endl;
select();
}
链表的创建,显示,删除,插入,寻找
最新推荐文章于 2022-06-13 00:02:13 发布