#include<bits/stdc++.h>
using namespace std;
typedef struct LNode{
int data;
struct LNode* next;
}LNode,*List;
//初始化
void InitList(List &L){
L=(LNode*)malloc(sizeof(LNode));
L->next=NULL;
}
//头插
void ListInsertHead(List &L,int e){
LNode* p=L;
LNode* s=(LNode*)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
}
//尾插
void ListInsertTail(List &L,int e){
LNode* p=L;
LNode* s=(LNode*)malloc(sizeof(LNode));
while(p->next!=NULL)
p=p->next;
s->data=e;
s->next=NULL;
p->next=s;
}
//中间插
void ListInsertMiddle(List &L,int i,int e){
LNode* p=L;
int j=0;
while(p!=NULL&&j<i-1){
p=p->next;
j++;
}
if(p==NULL){
cout<<"Insert Error:Element Not Found!"<<endl;
}else{
LNode* s=(LNode*)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
}
}
//删除
void ListDelete(List &L,int i){
LNode* p=L;
int j=0;
if(p==NULL)
cout<<"Delete Error:List Empty!"<<endl;
while(p!=NULL&&j<i-1){
p=p->next;
j++;
}
if(p==NULL||p->next==NULL){
cout<<"Delete Error:Element Not Found!"<<endl;
}else{
LNode* q=p->next;
p->next=q->next;
free(q);
}
}
//按序号查找
void GetElem(List L,int i){
LNode* p=L;
int j=0;
while(p!=NULL&&j<i){
p=p->next;
j++;
}
if(p==NULL)
cout<<"GetElem Error:LNode Not Defined!"<<endl;
else
cout<<"LNode NO."<<i<<" Found!"<<endl;
}
//按值查找
void LocateElem(List L,int e){
LNode* p=L->next;
while(p!=NULL&&p->data!=e)
p=p->next;
if(p==NULL)
cout<<"LocateElem Error:LNode Not Defined!"<<endl;
else
cout<<"LNode Value "<<e<<" Found!"<<endl;
}
//求表长
int Length(List L){
int len=0;
LNode* p=L;
while(p->next!=NULL){
p=p->next;
len++;
}
return len;
}
//打印
void PrintList(List L){
LNode* l=L->next;
while(l!=NULL){
cout<<l->data<<" ";
l=l->next;
}
cout<<"END"<<endl;
}
int main(){
List L;
InitList(L);
ListInsertHead(L,5);
ListInsertHead(L,3);
ListInsertHead(L,2);
ListInsertTail(L,7);
ListInsertTail(L,11);
ListInsertMiddle(L,3,4);
ListDelete(L,1);
PrintList(L);
cout<<"Length of LinkList:"<<Length(L)<<endl;
GetElem(L,6);
LocateElem(L,4);
return 0;
}
标签:单链,LNode,int,void,List,next,NULL,线性表
From: https://www.cnblogs.com/b1ackstar/p/18291088