参考 王道
#include<iostream>
#include<cstdio>
#include<malloc.h>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
LinkList List_HeadInsert(LinkList &L){
LNode *s;
int x;
L =(LNode*)malloc(sizeof(LNode));
L->next=NULL;
scanf("%d",&x);
while(x != 9999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;
L->next=s;
scanf("%d",&x);
}
return L;
}
LinkList List_TailInsert(LinkList &L){
int x;
L=(LNode *)malloc(sizeof(LNode));
LNode *s;
LNode *r=L;
scanf("%d",&x);
while(x!=9999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r=s;
scanf("%d",&x);
}
r->next=NULL;
return L;
}
LinkList GetElem(LinkList L,int i){
int j=1;
LNode *p=L->next;
if(i==0)
return L;
if(i<1)
return NULL;
while(p&&j<i){
p=p->next;
j++;
}
return p;
}
int PrintList(LinkList L){
LNode *p=L->next;
while(p->next!=NULL){
cout<<p->data<<"->";
p=p->next;
}
cout<<p->data;
cout<<endl;
return 0;
}
int LocateElem(LinkList L,int e){
int sum = 1;
LNode *p = L->next;
while(p!=NULL&&p->data!=e){
p=p->next;
sum++;
}
if(p==NULL)
return -1;
return sum;
}
void DeleteNode(LinkList &L,int i){
LNode *p=GetElem(L,i-1);
LNode *s=p->next;
p->next=s->next;
free(s);
}
void InsertNode(LinkList &L,int i,int e){
LNode *s=(LNode*)malloc(sizeof(LNode));
s->data=e;
LNode *p=GetElem(L,i-1);
s->next=p->next;
p->next=s;
}
int GetLen(LinkList L){
LNode *p = L->next;
int sum =1;
while(p->next!=NULL){
p = p->next;
sum++;
}
return sum;
}
int main(){
cout<<"建立链表 输入9999停止"<<endl;
LinkList L;
List_HeadInsert(L);
PrintList(L);
int i;
cout<<"请输入要查找的位置:"<<endl;
cin>>i;
LNode *s = GetElem(L,i);
cout<<"表中第"<<i<<"是"<<s->data<<endl;
int j;
cout<<"请输入要查找的值:"<<endl;
cin>>j;
cout<<"表中"<<j<<"位置是"<<LocateElem(L,j)<<endl;
cout<<"请输入要删除的位置:"<<endl;
int k;
cin>>k;
DeleteNode(L,k);
PrintList(L);
cout<<"请输入要插入的位置:"<<endl;
int l1;
cin>>l1;
cout<<"请输入要插入的值:"<<endl;
int l2;
cin>>l2;
InsertNode(L,l1,l2);
PrintList(L);
cout<<"表长为:"<<GetLen(L)<<endl;
return 0;
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200604163620807.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zODIyMDc5OQ==,size_16,color_FFFFFF,t_70)