#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define LEN sizeof(ARR)
typedef struct array{
int data;
struct array *pnext;
} ARR,*PARR;
struct array * link_list_creat(void );
void traval_list(PARR phead);
void add_link_list(PARR phead, int val);
void delete_list(PARR phead, int val);
void insert_list(PARR phead, int val, int nu);
void main(void)
{
PARR phead;
phead = link_list_creat();
traval_list( phead);
//add_link_list(phead,4);
// delete_list( phead ,1);
insert_list( phead, 2, 2);
traval_list( phead);
return ;
}
struct array * link_list_creat(void )
{
PARR phead;
PARR pnew,ptail;
int i, len,val;
phead=ptail=(PARR)malloc(LEN);
if(NULL==phead)
{
printf("分配内存空间失败!");
exit(-1);
}
ptail->pnext=NULL;
printf("请输入链表个数 length =");
scanf("%d",&len);
for(i=0;i<len;i++)
{
printf("你输入的第 %d 个数是 ", i+1);
scanf("%d",&val);
pnew=(PARR)malloc(LEN);
if(NULL==pnew)
{
printf("分配内存空间失败!");
exit(-1);
}
pnew->data=val;
ptail->pnext=pnew;
pnew->pnext=NULL;
ptail=pnew;
}
return phead;
}
void traval_list(PARR phead)
{
PARR p;
p=phead->pnext;
while(NULL != p)
{
printf("%d \n",p->data);
p=p->pnext;
}
return ;
}
void add_link_list(PARR phead, int val)
{
PARR p,ptail,pnew;
p=phead->pnext;
while(NULL != p->pnext)
{
p=p->pnext;
}
ptail=p;
pnew=(PARR)malloc(LEN);
if(NULL==pnew)
{
printf("分配内存空间失败!");
exit(-1);
}
pnew->data=val;
ptail->pnext=pnew;
pnew->pnext=NULL;
ptail=pnew;
return ;
}
void delete_list(PARR phead, int val)
{
int i=0;
PARR p,pp;
p=phead->pnext;
if(1==val)
{
phead->pnext =phead->pnext->pnext;
}
else
{
for(i=0;i<val-2;i++)
{
p=p->pnext;
}
pp=p->pnext;
p->pnext= (p->pnext)->pnext;
free(pp);
}
return ;
}
void insert_list(PARR phead, int val, int nu)
{ int i;
PARR p,ptail,pnew;
p=phead->pnext;
pnew=(PARR)malloc(LEN);
if(NULL==pnew)
{
printf("分配内存空间失败!");
exit(-1);
}
pnew->data=val;
if(1==nu)
{
phead->pnext =pnew;
pnew->pnext=p;
}
else
{
for(i=0;i<nu-2;i++)
{
p=p->pnext;
}
ptail=p->pnext;
p->pnext=pnew;
pnew->pnext= ptail;
}
return ;
}
*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。