这是我上数据结构时写的关于链表的程序
包括建立头结点,建立链表,头插法,链表的插入删除
恐怕这不是最好的,但希望能给你点帮助
# include <stdio.h>
# include <malloc.h>
# define NULL 0
# define LEN sizeof(struct node)
struct node{
int data;
struct node *next;
};
struct node * create_list(int n)
{
int i;
struct node *head,*p1,*p2;
head=p2=p1=(struct node *)malloc(LEN);
for(i=0;i<n;i++)
{
p1=(struct node *)malloc(LEN);
p2->next=p1;
p2=p1;
}
p2->next=NULL;
return(head);
}
void input(struct node * head)
{
struct node *p1;
p1=head->next;
while(p1)
{
scanf("%d",&p1->data);
p1=p1->next;
}
}
void output(struct node *head)
{
struct node *p2;
p2=head->next;
while(p2)
{
printf("%d ",p2->data);
p2=p2->next;
}
}
void headinsert_list(int *m,struct node *head)
{
struct node *p;
p=(struct node *)malloc(LEN);
printf("\nplease input the data in node p:\n");
scanf("%d",&p->data);
p->next=head->next;
head->next=p;
*m+=1;
}
void insert_list(int n,int *m,struct node *head)
{
int i;
struct node *p;
struct node *q;
p=head->next;
q=(struct node *)malloc(LEN);
if(n>*m)
{
printf("fail to insert\n");
}
else
{
for(i=1;i<=*m;i++)
{
if(i!=(n-1))
{
p=p->next;
}
else
{
printf("Please input the data in node q;\n");
scanf("%d",&q->data);
q->next=p->next;
p->next=q;
*m+=1;
printf("You have successfully inserted %d.\n",q->data);
break;
}
}
}
}
void delete_list(int n,int *m,struct node * head)
{
int i;
struct node *p1,*p2;
p1=head->next;
p2=head;
if(n>*m)
{
printf("fail to detele.\n");
}
else
{
for(i=1;i<=*m;i++)
{
if(i!=n)
{
p2=p1;
p1=p1->next;
}
else
{
p2->next=p1->next;
p1->next=NULL;
*m-=1;
printf("You have successfully deleted %d.\n",p1->data);
free(p1);
break;
}
}
}
}
void main()
{
struct node *head;
int seat1,seat2;
int len;
int *len_ptr;
len_ptr=&len;
printf("\nPlease input the length of the list:\n");
scanf("%d",&len);
head=create_list(len);
printf("\nNow,you will input the numbers into the list.\n");
input(head);
printf("\nNow,please check these data.\n");
output(head);
printf("\nlength is %d\n",*len_ptr);
headinsert_list(len_ptr,head);
output(head);
printf("\nlength is %d\n",*len_ptr);
printf("\nNow,please locate the inserted seat.\n");
scanf("%d",&seat1);
insert_list(seat1,len_ptr,head);
output(head);
printf("\nlength is %d\n",*len_ptr);
printf("\nNow,please locate the deleted seat.\n");
scanf("%d",&seat2);
delete_list(seat2,len_ptr,head);
output(head);
printf("\nlength is %d\n",*len_ptr);
}