#include<iostream>
#include<cstdlib>
using namespace std;
#define Elemtype int
typedef struct node {
struct node* next;
Elemtype data;
}node,*NL;//结构
NL init()
{
NL head = new node;
head->next = NULL;
return head;
}//初始化,分配一个节点作为链表头//初始化,分配一个节点作为链表头
int PUSH(NL n)//打印列表函数
{
if (!n)
{
printf("empty error\n");
return 0;
}
while (n->next)
{
n = n->next;
}
cout<<"\t\t\t\t\t输入添加的节点数值: ";
int data;
cin >> data;
NL nc = new node;
nc->next = NULL;
n->next = nc;
nc->data = data;
printf("\t\t\t\t添加成功\n");
}//天加节点的函数
int show_list(NL n)
{
if (!n || !(n->next))
{
printf("empty error\n");
return 0;
}
cout<<"\n\n\n\t\t\t\t\t";
while (n->next)
{
cout << n->next->data << "->";
n = n->next;
}
cout<<"空\n";
return 0;
}
int search_number(NL n)//搜索节点函数
{
bool found = false;
if (!n || !(n->next))
{
cout<<"empty error\n";
return 0;
}
cout<<"\t\t\t\t\t输入查询节点的值: ";
int data;
cin >> data;
int index = 0;
while (n->next)
{
if (n->next->data == data) {
cout << "\t\t\t\t\t" << data << "在第" << index << "位" << endl;;
found = true;
}
index++;
n = n->next;
}
if (!found)
cout<<"\t\t\t\t\t"<<data<<"不在名单上\n";
return 0;
}
int sort_list(NL n)
{
if (!n)
{
cout<<"empty error\n";
return 0;
}
NL ni = n;
NL na = n;
while (ni->next)
{
na = ni->next;
while (na->next)
{
if (ni->next->data > na->next->data)
ni->next->data ^= na->next->data ^= ni->next->data ^= na->next->data;
na = na->next;
}
ni = ni->next;
}
cout<<"\t\t\t\t\t排序成功\n";
}//排序函数
int delete_duplicate(NL n)
{
if (!n)
{
cout<<"empty error\n";
return 0;
}
while (n->next)
{
NL np = n->next;
while(np->next)
{
if (np->next->data == n->next->data)
{
NL ptr = np->next;
np->next = np->next->next;//从头节点的next开始遍历,如果后面有节点相同则释放
free(ptr);
}
np = np->next;
}
n = n->next;
}
return 0;
}//删除重复值函数
int delete_list(NL n)
{
while (n)
{
NL ptr = n;
n = n->next;
free(ptr);//根据链表特性不断释放空间
}
return 0;
}//删除链表函数
int menu()
{
int length;//定义初始时的链表长度
NL n = init();
cout<<"\n\n\n\t\t\t\t\t请输入一个数字: ";
cin >> length;
for (int i = 0; i < length; i++)
{
PUSH(n);//不断添加节点
}
while (1)
{
system("cls");//进入菜单
back://如果下面输出错误回到此处
cout<<"\n\n\n\t\t\t\t\t███████████████████████████████\n";
cout<<"\t\t\t\t\t█ █\n";
cout<<"\t\t\t\t\t█ 1) 添加数字 █\n";
cout<<"\t\t\t\t\t█ 2) 显示列表 █\n";
cout<<"\t\t\t\t\t█ 3) 搜索数字 █\n";
cout<<"\t\t\t\t\t█ 4) 列表排序 █\n";
cout<<"\t\t\t\t\t█ 5) 删除重复 █\n";
cout<<"\t\t\t\t\t█ 6) 删除列表 █\n";
cout<<"\t\t\t\t\t█ 0) 退出系统 █\n";
cout<<"\t\t\t\t\t█ █\n";
cout<<"\t\t\t\t\t██████████████████████████████\n";//菜单
cout<<"\n\t\t\t\t\t你的选择> ";
int choice;
cin >> choice;
switch (choice)
{
case 1:
PUSH(n);
break;
case 2:
show_list(n);
break;
case 3:
search_number(n);
break;
case 4:
sort_list(n);
break;
case 5:
delete_duplicate(n);
break;
case 6:
delete_list(n);
n = NULL;
break;
case 0:
exit(0);
default:
system("cls");
cout<<"\t\t\t\t\t输入错误请重新输入..";//输入错误回到back标签处
goto back;
}
cout<<"\t\t\t\t\t输入回车返回菜单\n";//等待回车,避免system("cls")将查询的信息清楚过快,使得人眼看不到
char wait = getchar();
wait = getchar();
}
}//菜单
int main(void)
{
menu();
return 0;
}