#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
using namespace std;
typedef struct node
{
int ans;
struct node *next;
}Node,*Linklist;
//初始化头结点
Linklist init(Linklist h)
{
h=(Node *)malloc(sizeof(Node));
h->next=NULL;
return h;
}
//头插法建立单链表
Linklist creat_head()
{
Linklist h,p;
int temp;
h=init(h);
cout<<"输入数据(遇0结束)"<<endl;
cin>>temp;
while(temp)
{
p=(Node *)malloc(sizeof(Node));
p->ans=temp;
p->next=h->next;
h->next=p;
cin>>temp;
}
cout<<"头插入创建链表成功"<<endl;
return h;
}
//尾插法建立单链表
Linklist creat_tail()
{
Linklist h,p,q;
int temp;
h=init(h);
q=h;
cout<<"输入数据(遇0结束)"<<endl;
cin>>temp;
while(temp)
{
p=(Node *)malloc(sizeof(Node));
p->ans=temp;
q->next=p;
q=p;
cin>>temp;
}
q->next=NULL;
cout<<"尾插入创建链表成功"<<endl;
return h;
}
//遍历单链表
void display(Linklist h)
{
Linklist p;
p=h->next;
while(p!=NULL)
{
cout<<p->ans<<endl;
p=p->next;
}
}
//删除操作
void delete_data(Linklist h)
{
int temp;
Linklist p,q;
p=h;
cout<<"输入要删除的元素值"<<endl;
cin>>temp;
while(p->next!=NULL)
{
if(p->next->ans==temp)
{
q=(Node *)malloc(sizeof(Node));
q=p->next;
p->next=p->next->next;
free(q);
break;
}
else p=p->next;
}
cout<<"删除成功"<<endl;
}
//插入操作
void add_data(Linklist h)
{
Linklist p,q;
int temp;
p=h;
cout<<"输入要插入的结点位置(在此节点之前插入元素)"<<endl;
cin>>temp;
for(int i=0;i<temp-1;i++)
p=p->next;
cout<<"输入要插入的元素"<<endl;
cin>>temp;
q=(Node *)malloc(sizeof(Node));
q->ans=temp;
q->next=p->next;
p->next=q;
cout<<"插入元素成功"<<endl;
}
//逆置单向链表
void Inverse_list(Linklist h)
{
Linklist p,q;
p=h->next;
h->next=NULL;
while(p!=NULL)
{
q=p;
p=p->next;
q->next=h->next;
h->next=q;
}
cout<<"逆置成功"<<endl;
}
int main()
{
Linklist h;
h=creat_head();
display(h);
h=creat_tail();
display(h);
delete_data(h);
display(h);
add_data(h);
display(h);
Inverse_list(h);
display(h);
return 0;
}