# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
# define NULL 0
# define LEN sizeof(struct node)
struct node{
int data;
struct node *next;
};
struct node *Head;
struct node * Init_list(void)
{
struct node *head;
head=(struct node *)malloc(LEN);
if(head)
{
head->next=NULL;
}
return (head);
}
struct node * creat_list(int n)
{
int i;
struct node *p1,*p2,*p3;
p3=p2=(struct node *)malloc(LEN);
for(i=0;i<n;i++)
{
p1=(struct node *)malloc(LEN);
p2->next=p1;
p2=p1;
i++;
}
p2->next=NULL;
return(p3);
}
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 insert_list(int n,int m,struct node *head)
{
int i;
struct node *p;
struct node *q;
p=head;
q=(struct node *)malloc(LEN);
printf("Please input the data in node q;\n");
if(n>m)
{
printf("fail to insert\n");
}
for(i=0;i<=m;i++)
{
if(i!=n)
{
p++;
}
else
{
q->next=p->next;
p->next=q;
m+=1;
printf("Success.\n");
}
}
}
void delete_list(int n,int m,struct node * head)
{
int i;
struct node *p1,*p2;
p1=head;
if(n>m)
{
printf("fail to detele.\n");
}
for(i=0;i<m;i++)
{
if(i!=n)
{
p2=p1;
p1=p1->next;
}
else
{
p2->next=p1->next;
p1->next=NULL;
m-=1;
printf("Success.\n");
printf("delete %d\n",p1->data);
}
}
}
void main()
{
struct node *p,*q;
int m,n;
int Len=0;
Head=Init_list();
printf("Please input the length of the list:\n");
scanf("%d,&Len");
Head->next=creat_list(Len);
printf("Now,you will input the numbers into the list.\n");
input(Head);
printf("Now,please check these data.\n");
output(Head);
p=(struct node *)malloc(LEN);
p->next=Head->next;
Head->next=p;
q=(struct node *)malloc(LEN);
printf("Now,please locate the inserted seat.\n");
scanf("%d",&n);
insert_list(n,Len,Head);
output(Head);
printf("Now,please locate the deleted seat.\n");
scanf("%d",&m);
delete_list(m,Len,Head);
output(Head);
printf("\n");
}
链表的创建,插入,删除