您的位置:首页 > 其它

不带表头结点的单向链表基本操作

2019-02-27 15:33 1011 查看
[code]
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *next;
};
typedef struct node Node;
typedef struct node *Link;

void create_head(Link *head)
{
*head=NULL;
}//不带头结点的单向链表,表头初始化为空

void create_node(Link *new_node)
{
*new_node=(Link)malloc(sizeof(Node));
}//给结点分配空间

void insert_node_head(Link *head,Link new_node)
{
new_node->next=*head;
*head=new_node;
}//头插法,各结点插于表头,与带头结点的单向链表操作一致

void insert_node_tail(Link *head,Link new_node)
{
Link p;
p=*head;
if(p==NULL)
{
*head=new_node;
new_node->next=NULL;
}
else
{
while(p->next!=NULL)
{
p=p->next;
}
p->next=new_node;
new_node->next=NULL;
}
}//尾插法,先判断表头是否为空

void insert_node_mid_before(Link *head,Link new_node, int insertlocation)
{
Link p,q;
p=*head;
if(p==NULL)
{
printf("link is empty!\n");
free(new_node);
return;
}
else
{
while(p!=NULL&p->num!=insertlocation)
{
q=p;
p=p->next;
}
if(p==NULL)
{
printf("no location to insert!\n");
return;
}
else
{
new_node->next=p;
q->next=new_node;

}
}
}//中间插入,在new_node->num=insertloction前面插入

void insert_node_mid_after(Link *head,Link new_node,int insertlocation)
{
Link p,q;
p=q=*head;
if(q==NULL)
{
printf("the link is empty!\n");
}
else
{
while(q!=NULL&&q->num!=insertlocation)
{
q=p;
p=p->next;
}
if(q==NULL)
{
printf("no location to insert!\n");
}
else
{
q->next=new_node;
new_node->next=p;
}
}
}

void delete_node(Link *head,int deletenum)
{
Link p,q;
p=q=*head;
if(p==NULL)
{
printf("the link is empty!\n");
return;
}
else
{
while(p->next!=NULL&&p->num!=deletenum)
{
q=p;
p=p->next;
}
if(p->next==NULL)
{
printf("no location to delete!\n");
}
else
{
q->next=p->next;
free(p);
}
}
}

void display(Link head)
{
Link p=head;
if(p==NULL)
{
printf("the link is empty!\n");
}
while(p!=NULL)
{
printf("num=%d\n",p->num);
p=p->next;
}
}//回显函数

void release(Link *head)
{
Link p;
p=*head;
if(*head==NULL)
{
printf("the link is empty!\n");
}
while(*head!=NULL)
{
*head=(*head)->next;
free(p);
p=*head;
}
}//释放包括头结点所有结点

int main()
{
Link head,new_node;
int i;
int insertlocation;
int deletenum;
create_head(&head);
for(i=0;i<10;i++)
{
create_node(&new_node);
new_node->num=i+1;
//insert_node_head(&head,new_node);
insert_node_tail(&head,new_node);
}
display(head);

create_node(&new_node);
printf("enter insert numbers:\n");
scanf("%d",&new_node->num);
printf("enter insertlocation:\n");
scanf("%d",&insertlocation);
insert_node_mid_after(&head,new_node,insertlocation);
display(head);

printf("enter delete num:\n");
scanf("%d",&deletenum);
delete_node(&head,deletenum);
display(head);

release(&head);
display(head);
return 0;
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: