#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node * next;
};
typedef struct node Node;
typedef struct node * Link;
void create_node(Link * new_node)
{
*new_node=(Link)malloc(sizeof(Node));
}
void create_head(Link *head)
{
*head=(Link)malloc(sizeof(Node));
(*head)->next=NULL;
}//带头结点的单向链表初始化
void insert_node_head(Link head,Link new_node)
{
Link p=head;
new_node->next=p->next;
p->next=new_node;
}//头插法插在首结点之前(头结点之后)
void insert_node_tail(Link head,Link new_node)
{
Link p = head;
while(p->next != NULL)
{
p=p->next;
}
if(p->next == NULL)
{
p->next=new_node;
new_node->next=NULL;
}
}//尾插法,插在最后结点后面,与无头结点的单向链表相比,不用判断首结点是否为空
void insert_node_mid_before(Link head,Link new_node,int insertlocation)
{
Link p,q;
p=q=head;
if(p==NULL)
{
printf("the link is empty!\n");
free(new_node);
}
else
{
while(p!=NULL&&p->num!=insertlocation)
{
q=p;
p=p->next;
}
if(p==NULL)
{
printf("no place to insert!\n");
}
else
{
new_node->next=p;
q->next=new_node;
}
}
}
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");
free(new_node);
return;
}
else
{
while(q!=NULL&&q->num!=insertlocation)
{
q=p;
p=p->next;
}
if(q==NULL)
{
printf("no place to insert!\n");
}
else
{
new_node->next=p;
q->next=new_node;
}
}
}
void delete_node(Link head,int deletenum)
{
Link p,q;
p=head;
if(p==NULL)
{
printf("the link is empty!\n");
}
else
{
while(p->next!=NULL&&p->next->num!=deletenum)
{
q=p;
p=p->next;
}
if(p->next==NULL)
{
printf("no num to delete!\n");
}
else
{
q=p->next;
p->next=p->next->next;
free(q);
}
}
}
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=*head;
if(p==NULL)
{
printf("the link is empty!\n");
}
while(p!=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);
// insert_node_mid_before(head,new_node,insertlocation);
display(head);
printf("enter deletenum:\n");
scanf("%d",&deletenum);
delete_node(head,deletenum);
display(head);
release(&head);
display(head);
return 0;
}
此处带头结点的单向链表插入操作我都定义了两个指针p,q;方便与之前不带头结点的单链表基本操作进行比较1.创建结点,释放结点均用二级指针2中间插入法一致
此外,统计链表结点数也一致