#include <stdio.h>
#include <stdlib.h>
struct node
{
int num ;
struct node * next ;
};
typedef struct node Node;
typedef struct node * Link ;
void create_link(Link *head)
{
*head = NULL ;
}
void is_malloc_ok(Link new_node)
{
if(new_node == NULL)
{
printf(“malloc error!\n”);
exit(-1);
}
}
void create_node(Link *new_node)
{
*new_node = (Link)malloc(sizeof(Node));
is_malloc_ok(*new_node);
}
void insert_node_head(Link *head,Link new_node)
{
new_node->next = *head ;
*head = new_node ;
}
void display_link(Link head)
{
Link p = head ;
if(head == NULL)
{
printf("link is empty\n");
return ;
}
while(p != NULL)
{
printf("%d\n",p->num);
p = p->next ;
}
}
void release_link(Link *head)
{
Link p = *head;
while(*head != NULL)
{
*head = (*head)->next;
free(p);
p = *head ;
}
}
void insert_node_tail(Link *head,Link new_node)
{
Link p = *head;
if(*head == 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(Link *head,Link new_node,int loc)
{
Link p = *head;
while(p != NULL && p->num != loc)
{
p = p->next ;
}
new_node->next = p->next ;
p->next = new_node ;
}
int node_amount(Link head)
{
int i = 0 ;
Link p = head;
while(p != NULL)
{
i++;
p = p->next ;
}
printf("链表的节点数为:%d\n",i);
return i ;
}
int main()
{
Link head = NULL;
Link new_node = NULL ;
int i ,loc;
create_link(&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_link(head);
create_node(&new_node);
printf("输入要插入的数:\n");
scanf("%d",&new_node->num);
printf("输入要插在第几个节点:\n");
scanf("%d",&loc);
insert_node_mid(&head,new_node,loc);
display_link(head);
node_amount(head);
release_link(&head);
display_link(head);
return 0;
}