两个月前打的,有点丑hhh。
//单链表
#include<iostream>
using namespace std;
#define Elemtype int
#include<malloc.h>
#include<string>
typedef struct Node{
int data;
struct Node* next;
}Node,*LinkList;
//尾插法
int TailInsert(LinkList L)
{
Node* p;int e;
p=L;
while(p->next!=NULL)
{
p=p->next;
}
cout<<"请输入要插入的整数(00结束):"<<endl;
cin>>e;
while(e!=00)
{
Node* NewNode=(Node*)malloc(sizeof(Node));
p->next=NewNode;
NewNode->data=e;
p=p->next;
L->data++;
cout<<"请输入要插入的整数(00结束):"<<endl;
cin>>e;
}
p->next=nullptr;
return 0;
}
//遍历
int PrintLinkList(LinkList L)
{
if(L->next==nullptr)
{
cout<<"该链表为空!遍历个毛!"<<endl;
}
else
{
Node* p=L->next;int e;
while(p->next!=NULL)
{
e=p->data;
cout<<e<<"==>";
p=p->next;
}
e=p->data;
cout<<e<<"==>";
p=p->next;
p=nullptr;
cout<<"nullptr"<<endl;
}
}
//遍历查找值
int GetElemtype(LinkList L,Elemtype e)
{
Node* p=L;int count=0;
while(p)
{
p=p->next;
count++;
if(p->next==nullptr&&p->data!=e)
{
cout<<"查找失败!该链表没有该值"<<endl;
break;
}
if(e==p->data)
{
cout<<"找到该元素!"<<endl;
cout<<"该元素在第"<<count<<"位!"<<endl;
break;
}
}
cout<<"若想查找其他值在第几位,请输入“love”"<<endl;
}
//擦除(按值删除)
int EraseElemtype(LinkList &L,Elemtype &e)
{
Node* p=L;
Node* q;
while(p->next!=nullptr)
{
if(e==p->next->data)
{
q=p->next;
e=q->data;
p->next=q->next;
delete q;
cout<<"删除后的链表为:"<<endl;
PrintLinkList(L);
cout<<"若还想删除,请输入“我爱你”"<<endl;
return 0;
}
else
{
p=p->next;
}
}
if(p&&e!=p->data){
cout<<"该链表为没有该值!删个毛!"<<endl;
PrintLinkList(L);
cout<<"若还想删除,请输入“我爱你”"<<endl;
return 0;
}
}
//选择
void Selectfunction(LinkList L)
{
int e;
cout<<"请选择(1)查找 (2)删除 (3)嫌烦就清屏"<<endl;
cin>>e;
if(e==1)
{
int m;
cout<<"请输入要查找的值!"<<endl;
cin>>m;
GetElemtype(L,m);
string k;
cin>>k;
if(k=="love")
{
Selectfunction(L);
PrintLinkList(L);
}
else return;
}
else if(e==2)
{
int m;
cout<<"请输入要删除的值!"<<endl;
cin>>m;
EraseElemtype(L,m);
string k;
cin>>k;
if(k=="我爱你")
{
Selectfunction(L);
}
else return;
}
else if(e==3)
{
system("cls");
system("pause");
Selectfunction(L);
}
else
{
Selectfunction(L);
}
}
int main()
{
//初始化
LinkList L;
L=(Node*)malloc(sizeof(Node));
L->data=0;
L->next=nullptr;
TailInsert(L);
PrintLinkList(L);
Selectfunction(L);
}
插入功能懒得写了(狗头保命)