#include <stdio.h>
#include <malloc.h>
#define N 8
typedef struct node
{int data;
struct node *next;
}node;
node * createsl()
{
node *p,*s,*h;
int j=1,x;
p=s=h=(node*)malloc(sizeof(node));
h->next=NULL;
printf("please input the data to create the list,end with -1 or %d nupmbers\n",N);
while(x!=-1&&j<=N)
{
printf("number %d:",j);
scanf("%d",&x);
s=(node*)malloc(sizeof(node));
s->data=x;
if(h->next==NULL)
h->next=s;
else
p->next=s;
p=s;
j++;
}
p->next=NULL;
return h;
}
int access(node *h,int i)
{
node *p;int j=1;
p=h->next;
while(p!=NULL)
{
if(p->data==i)
break;
p=p->next;
j++;
}
if(p!=NULL)
{
printf("find the number in position:%d\n",j);
return(p->data);
}
else
{
printf("can't find the number in the list!\n");
return -1;
}
}
void insertsl(node *h,int i)
{
node *p,*t;
int j=1;
p=h->next;;
while(p->next!=NULL)
{
p=p->next;
j++;
}
t=(node*)malloc(sizeof(node));
t->data=i;
t->next=p->next;
p->next=t;
printf("insert success in position %d\n",j+1);
}
void deletesl(node *h,int i)
{
node *p,*s,*q;
int j=1;
p=h;
while(p->next!=NULL)
{
q=p->next;
if(q->data==i)
break;
p=p->next;
j++;
}
if(p->next==NULL)
{
printf("Can't find the number you want to delete.\n");
return;
}
else
{
s=p->next;
p->next=s->next;
free(s);
printf("delete success in position %d\n",j+1);
}
}
void print(node *h)
{
printf("\nprint all the data in the list:") ;
node *s;
s=h->next;
if(s!=NULL)
{
while(s!=NULL)
{
printf(" %d ",s->data) ;
s=s->next;
}
}
else
printf("the list is empty!%d");
printf("\n");
}
int main()
{
node *p;
int a;
p=createsl() ;
printf("\nyou need find the number:\n");
scanf("%d",&a);
access(p,a);
printf("\nplease input the number you want to insert:\n");
scanf("%d",&a);
insertsl(p,a);
printf("\nplease input the number you want to delete:\n");
scanf("%d",&a);
deletesl(p,a);
print(p);
return 0;
}
温馨提示:答案为网友推荐,仅供参考