线性表-链式存储(单链表)
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define MAXSIZE 10000
#define SUCCESS 0
#define OVERFLOW 0
#define ERROR -1
typedef int ElemType;
typedef int Status;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
Status InitList(LinkList &L);
Status PrintElem(LinkList L);
Status InitElem(LinkList &L,ElemType e[],int len);
void CreateList_H(LinkList &L,int n);
void CreateList_R(LinkList &L,int n);
Status GetElem(LinkList L,int i,ElemType &e);
LNode *LocateElem(LinkList L,ElemType e);
Status ListInsert(LinkList &L,int i,ElemType e);
Status ListDelete(LinkList &L,int i);
int main(){
LinkList L,L1,L2;
ElemType elem[]={4,5,2,1,25,3,6,5},e=1;
InitList(L);
InitElem(L,elem,8);
printf("\nplease enter 3 numbers:");
CreateList_H(L1,3);
printf("\nplease enter 3 numbers:");
CreateList_R(L2,3);
printf("\ne=%d",e);
GetElem(L,1,e);
printf("\ne=%d",e);
printf("\n1--Locate=%d",LocateElem(L,1)->data);
ListInsert(L,3,7);
ListDelete(L,3);
return 0;
}
Status InitList(LinkList &L)
{
L=new LNode;
L->next=NULL;
printf("init\n");
return SUCCESS;
}
Status PrintElem(LinkList L)
{
LinkList p=L->next;
printf("\n");
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
return SUCCESS;
}
Status InitElem(LinkList &L,ElemType e[],int len)
{
int i;
LNode *p;
for(i=0;i<len;i++){
p=new LNode;
p->data=e[i];
p->next=L->next;
L->next=p;
printf("%d ",e[i]);
}
PrintElem(L);
return SUCCESS;
}
void CreateList_H(LinkList &L,int n){
LNode *p;int i;
L=new LNode;
L->next=NULL;
for(i=0;i<n;++i){
p=new LNode;
cin>>p->data;
p->next=L->next;
L->next=p;
}
PrintElem(L);
}
void CreateList_R(LinkList &L,int n){
LNode *p,*r;int i;
L=new LNode;
L->next=NULL;
r=L;
for(i=0;i<n;++i){
p=new LNode;
cin>>p->data;
p->next=NULL;
r->next=p;
r=p;
}
PrintElem(L);
}
Status GetElem(LinkList L,int i,ElemType &e)
{
LNode *p=L->next;int j=1;
while(p&&j<i){
p=p->next;
++j;
}
if(!p||j>i) exit(ERROR);
e=p->data;
return SUCCESS;
}
LNode *LocateElem(LinkList L,ElemType e)
{
LNode *p=L->next;
while(p&&p->data!=e)
p=p->next;
return p;
}
Status ListInsert(LinkList &L,int i,ElemType e)
{
LNode *p=L,*s;int j=0;
while(p&&(j<i-1)){
p=p->next;++j;
}
if(!p||j>i-1) exit(ERROR);
s=new LNode();
s->data=e;
s->next=p->next;
p->next=s;
PrintElem(L);
return SUCCESS;
}
Status ListDelete(LinkList &L,int i)
{
LNode *p=L,*q;int j=0;
while((p->next)&&(j<i-1)){
p=p->next;++j;
}
if(!(p->next)||j>i-1) exit(ERROR);
q=p->next;
p->next=q->next;
delete q;
PrintElem(L);
return SUCCESS;
}