一个单链表的创建,插入,删除的程序
#include<stdio.h>#include<malloc.h>
#include<stddef.h>
#define NULL 0
typedef struct node_type
{
int data;
struct node_type*next;
}node_type;
typedef struct list_type
{
node_type*head;
node_type*tail;
int length;
}list_type;
void create_list(list_type*list)
{
node_type*new_node;
int x,i;
list->head=NULL;
list->tail=NULL;
list->length=0;
for(i=0;i<5;i++)
{
scanf("%d",&x);
new_node=(node_type*)malloc(sizeof(struct node_type));
new_node->data=x;
new_node->next=NULL;
if(list->length<=0)
{
new_node->next=list->head;
list->head=new_node;
}
else
{
new_node->next=list->head;
list->head=new_node;
}
list->length++;
}
}
void show(list_type*list)
{
int i=0;
node_type*p;
for(p=list->head;i<list->length&&p!=NULL;i++)
{
printf("%6d",p->data);
p=p->next;
}
printf("\n");
}
void insert(list_type*list,int x,int location)
{
int i;
node_type*new1,*p;
new1=(node_type*)malloc(sizeof(struct node_type));
new1->data=x;
new1->next=NULL;
p=list->head;
for(i=0;i<location-2;i++)
p=p->next;
new1->next=p->next;
p->next=new1;
list->length++;
}
void delet(list_type*list,int location)
{
int i;
node_type*p;
p=list->head;
for(i=0;i<location-2;i++)
p=p->next;
p->next=p->next->next;
list->length--;
}
void main()
{
int i,j,x;
list_type list;
create_list(&list);
show(&list);
printf("\n");
scanf("%d",&i);
scanf("%d",&x);
insert(&list,x,i);
show(&list);
printf("\n");
scanf("%d",&j);
delet(&list,j);
show(&list);
printf("\n");
}