c语言单链表的建立与维护

来源:百度知道 编辑:UC知道 时间:2024/05/18 03:50:00
#define n8
struct node
{int data;
struct node *next;
};
void createsl(node*h)
{struct node *p,*s;
int j,x;
h=(node*)malloc(sizeof<node));
h->next=NULL;
j=j+1;
printf("\n please input:%d",j);
scanf("%d",&x);
while(x!=-1)
{s=(node*)malloc(sizeof(node));
s->data=x;
if(h->next==NULL)
h->next=s;
else p->next=s;
p=s;
}
p->next=NULL;
}
int access(node *h,int i)
{node *p;int j;
p=h;j=0;
while(p->next!=NULL&&j<i)
{p=p->next;
j++;
}
if(p!=NULL&&j=i)
return(p->data);
else return(NULL);
}
void insertsl(node *h,int i)
{node *p,*t;
int j;
p=h;j=0;
while(p!=NULL&&j<i-1)
{p=p->next;
j++;
}
if(j!=i-1)
{printf("i is invalid.\n");
return;
}
t=(node*)malloc(sizeof(node));<

修改如下:
删除与插入是按值的。
#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)