#include <stdio.h>
#include <stdlib.h>
#define ERROR NULL
typedef struct LNode *PtrToLNode;
struct LNode{
int data;
PtrToLNode next;
};
typedef PtrToLNode Position;
typedef PtrToLNode List;
List MakeEmpty(){
List L;
L=(List)malloc(sizeof(struct LNode));
if(!L)
exit(-1);
L->next=NULL;
return L;
}
List Insert(List L ,int x,int i){
Position temp,p=L;
int count =0;
while(p && count<i-1){
p = p->next;
count++;
}
if(p==NULL||count!=i-1){
printf("插入位置参数错误\n");
return ERROR;
}
else{
temp = (Position)malloc(sizeof(struct LNode));
temp->data=x;
temp->next=p->next;
p->next=temp;
return L;
}
}
bool Delete(List L,int i){
Position temp,pre=L;
int count=0;
while(pre && count<i-1){
pre=pre->next;
count++;
}
if(pre==NULL || count!=i-1 || pre->next==NULL){
printf("删除的位置不合法!");
return false;
}else{
temp=pre->next;
pre->next=temp->next;
free(temp);
return true;
}
}
int Find(List L,int i){
Position p=L->next;
int count=1;
while(p && count<i){
p=p->next;
count++;
}
if(p && count==i){
return printf("查找的元素为:%d",p->data);
}else{
return ERROR;
}
}
int Length(List L){
Position p=L->next;
int count=0;
while(p){
p=p->next;
count++;
}
return count;
}
void output(List L)
{
List p = L->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
}
void main(){
List L=MakeEmpty();
int num,x,del,find;
printf("请输入数据个数:");
scanf("%d",&num);
for(int i=1;i<=num;i++){
scanf("%d",&x);
Insert(L,x,i);
}
output(L);
printf("\n");
printf("请输入查找的下标:");
scanf("%d",&find);
Find(L,find);
printf("\n");
printf("请输入要删除的位置:");
scanf("%d",&del);
Delete(L,del);
output(L);
printf("\n");
int l=Length(L);
printf("数组长度为:%d",l);
printf("\n");
}
转载请注明原文地址:https://blackberry.8miu.com/read-16104.html