#include
#include
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int ET;
#define MAXSIZE 100
单链表的存储结构
typedef struct Lnode
{
ET data; //结点的数据域
struct Lnode *next;//结点的指针域
}Lnode, *linklist; //linklist为指向结构体Lnode的指针类型
///初始化单链表
Status Initlist(linklist *L)//L是个二级指针
{
(*L) = (linklist)malloc(sizeof(Lnode));//动态分配新的单链表空间
(*L)->next = NULL;//初始化指针域为空
return OK;
}
///头插法创建单链表
void Createlist(linklist L, int n)
{
for(int i=0;idata = data;
p->next = L->next;
L->next = p;
}
}
单链表取值
Status Getelem(linklist L, int i, ET* e)
{
linklist p = L; int j = 1;
for(;j<=i;j++)
{
if( p == NULL ) return ERROR;
p = p->next;
}
if(j>i+1) return ERROR;
*e = p->data;
return OK;
}
///单链表查找
linklist Searchelem(linklist L,ET e)
{
linklist p = L->next;
while(p)
{
if( p->data == e ) return p;
p = p->next;
}
return NULL;
}
//单链表的插入
Status Insert(linklist L, int n, ET e)
{
linklist p = L->next;
int j=1;
n--;
while(p&&jnext;
j++;
}
if(!p||j>n) return ERROR;
linklist r=(linklist)malloc(sizeof(Lnode));
r->next = p->next;
p->next = r;
r->data = e;
return OK;
}
//单链表的删除
Status delete(linklist L, int n)
{
linklist p = L->next;
int j=1;
n--;
while(p&&jnext;
++j;
}
if(!p||j>n) return ERROR;
p->next = p->next->next;
return OK;
}
查看单链表
void browselist(linklist L)
{
linklist p = L->next;
printf("the list is:");
while(p){
printf("%d ",p->data);
p = p->next;
};
}
int main(void)
{
printf("please input the total number of the elems:");
int n;
scanf("%d",&n);
printf("please input each number of the elems:");
linklist L,p;
Initlist(&L);
Createlist(L,n);
browselist(L);
//测试取值功能
int k;
ET q;
printf("nplease input the number of the elem:");
scanf("%d",&k);
Getelem(L,k,&q);
printf("%d",q);
//测试查找功能
ET r;
printf("nplease input the elem u want to find:");
scanf("%d",&r);
printf("%p",Searchelem(L,r));
//测试插入功能
ET w;
int a;
printf("nplease input the elem u want to insert and to where");
scanf("%d %d",&w,&a);
Insert(L,a,w);
browselist(L);
//测试删除功能
int b;
printf("nplease input the number of the elem u want to delete:");
scanf("%d",&b);
delete(L,b);
browselist(L);
system("pause");
return 0;
}