顺序表的链式实现(C语言)
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data
;
struct node
*next
;
}Node
,*LinkList
;
void InitList(LinkList
*L
)
{
*L
=(LinkList
)malloc(sizeof(Node
));
(*L
)->next
=NULL;
}
void HeadInsert(Node
*L
)
{
Node
*s
;
char z
;
int x
;
do{
scanf("%d",&x
);
s
=(LinkList
)malloc(sizeof(Node
));
s
->data
=x
;
s
->next
=L
->next
;
L
->next
=s
;
}while((z
=getchar())!='\n');
}
void TailInsert(Node
*L
)
{
int x
;
char z
;
Node
*s
,*r
;
r
=L
;
do{
scanf("%d",&x
);
s
=(LinkList
)malloc(sizeof(Node
));
s
->data
= x
;
r
->next
= s
;
r
= s
;
}while((z
=getchar())!='\n');
r
->next
=NULL;
}
int GetElem(Node
*L
,int i
)
{
Node
*p
=L
->next
;
int j
=1;
if(i
==0)
return 0;
if(i
<0)
return -1;
while(p
&&j
<i
){
p
=p
->next
;
j
++;
}
return p
->data
;
}
Node
*Insert(Node
*L
,int index
,int add
)
{
Node
*p
=L
->next
,*s
,*q
;
int i
;
for(i
=1;i
<index
-1;i
++){
p
=p
->next
;
if(p
==NULL){
printf(" 插入无效");
return p
;
}
}
s
=(LinkList
)malloc(sizeof(Node
));
s
->data
=add
;
s
->next
=p
->next
;
p
->next
=s
;
return L
;
}
Node
*Delete(Node
*L
,int i
)
{
Node
*p
=L
,*del
;
int j
=1;
while(p
->next
&&j
<i
)
{
p
=p
->next
;
++j
;
}
del
= p
->next
;
p
->next
=del
->next
;
return L
;
}
void print(Node
*L
)
{
Node
*q
,*p
=L
;
q
=p
->next
;
while(q
!=NULL)
{
printf("%d ",q
->data
);
q
=q
->next
;
}
printf("\n");
}
main()
{
Node
*p1
= NULL;
InitList(&p1
);
TailInsert(p1
);
p1
=Delete(p1
,2);
print(p1
);
return 0;
}
转载请注明原文地址:https://tech.qufami.com/read-18371.html