#include<iostream>
#include<malloc.h>
#include<stdlib.h>
using namespace std;
struct node{
int data;
node* next;
};
typedef node* lklist;
typedef node* pointer;
lklist CreatListF()
{
pointer head,p;
head=(lklist)malloc(sizeof(node));
head->next=NULL;
int i;
int n;
cout<<"请输入你要的元素个数"<<endl;
cin>>n;
cout<<"请输入"<<n<<"个数"<<endl;
for(i=n;i>0;--i)
{
p=(lklist)malloc(sizeof(node));
cin>>p->data;
p->next=head->next;
head->next=p;
}
return head;
}
int Length(lklist L)
{
lklist p;
p=L->next;
int len=0;
while(p!=NULL)
{
p=p->next;
len++;
}
cout<<"线性链表的长度为:"<<len<<endl;
}
int Destroyed(lklist L)
{
pointer p,q;
p=L->next;
while(p!=NULL)
{
q=p->next;
free(p);
p=q;
}
L->next=NULL;
cout<<"销毁成功"<<endl;
/* pointer p;
while (L)
{
p = L;
L = L->next;
free(p);
} // while
cout<<"销毁成功"<<endl; */
}
int emptylist(lklist L)
{
if(L->next==NULL)
cout<<"链表为空"<<endl;
else
cout<<"链表不为空"<<endl;
}
int get(lklist head,int n)
{
int i;
pointer p;
p=head;
i=-1;
while(p!=NULL)
{
i++;
if(i==n)
break;
p=p->next;
}
return p->data;
}
int Qian(lklist head,int i)
{
int j;
pointer p;
p=head;
j=0;
while(p->next&&j<i-1)
{
p=p->next;++j;
}
if(j==0)
cout<<"该位置不存在前驱!!!"<<endl;
else cout<<p->data<<endl;
/*int i;
cout<<"请输入元素位置"<<endl;
cin>>i;
cout<<"该位置前驱为"<<get(head,i-1)<<endl;*/
}
int Hou(lklist head,int i)
{
int j;
pointer p;
p=head;
j=0;
while(p->next&&j<i+1)
{
p=p->next;++j;
}
if(j==i)
cout<<"该位置不存在后继!!!"<<endl;
else cout<<p->data<<endl;
/* int i;
cout<<"请输入元素位置"<<endl;
cin>>i;
cout<<"该位置前驱为"<<get(head,i+1)<<endl;*/
}
int Cha(lklist head,int i,int n)
{
pointer p;
p=head;
int j;
j=0;
while(p->next&&j<i-1)
{
p=p->next;++j;
}
lklist s;
s=(lklist)malloc(sizeof(node));
cin>>s->data;
s->next=p->next;
p->next=s;
cout<<"操作完成!!!"<<endl;
}
int Delete(lklist head,int i,int n)
{
pointer p;
p=head;
int j;
j=0;
while(p->next&&j<i-1)
{
p=p->next;++j;
}
lklist q;
q=p->next;
p->next=q->next;
free(q);
cout<<"操作完成!!!"<<endl;
}
int Xian(lklist head)
{
pointer p;
p=head;
int j;
if(p->next==NULL)
cout<<"链表不存在!!!"<<endl;
else while(p->next)
{
p=p->next;
cout<<p->data<<" ";
}
cout<<endl;
}
int show()
{
cout<<"0----创建链表"<<endl;
cout<<"1----销毁线性表"<<endl;
cout<<"2----判断线性表是否为空"<<endl;
cout<<"3----求线性表长度"<<endl;
cout<<"4----获取线性表指定位置元素"<<endl;
cout<<"5----求前驱"<<endl;
cout<<"6----求后继"<<endl;
cout<<"7----在线性表指定位置前插入元素"<<endl;
cout<<"8----删除线性表指定位置元素"<<endl;
cout<<"9----显示线性表"<<endl;
cout<<" 退出,输出一个负数!"<<endl;
}
int main()
{
lklist L;
show();
int n;
while(1)
{
cout<<"请输入您想要进行的操作"<<endl;
cin>>n;
if(n==0)
L=CreatListF();
if(n==1)
Destroyed(L);
if(n==2)
emptylist(L);
if(n==3)
Length(L);
if(n==4)
{
int a;
cout<<"请输入您想要获取元素的位置"<<endl;
cin>>a;
cout<<a<<"上的元素是"<<get(L,a)<<endl;
}
if(n==5)
{
int i;
cout<<"请输入你要找的位置"<<endl;
cin>>i;
Qian(L,i);
}
if(n==6)
{
int i;
cout<<"请输入你要找的位置"<<endl;
cin>>i;
Hou(L,i);
}
if(n==7)
{
int i;
cout<<"请输入你要插的位置"<<endl;
cin>>i;
cout<<"请输入你要插入元素的值"<<endl;
Cha(L,i,n);
}
if(n==8)
{
int i;
cout<<"请输入你要删除的位置"<<endl;
cin>>i;
Delete(L,i,n);
}
if(n==9)
{
Xian(L);
}
}
}