链表的头插 尾插等操作
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
/* char name[30];
char sex;
int age;
char add[30];*/
struct node * next;
};
typedef struct node Node;
typedef struct node * Link;
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 create_link(Link * head)
{
*head = NULL;
}
void insert_node_head(Link * head,Link new_node)
{
new_node->next = *head;
*head = new_node;
}
void display_link(Link head)
{
Link p;
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;
p = *head;
while(*head != NULL)
{
*head = (*head)->next;
free(p);
p = *head;
}
}
void insert_node_tail(Link * head,Link new_node)
{
Link p;
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,q;
p = q = *head;
if((*head)->num == loc)
{
new_node->next = *head;
*head = new_node;
}
else
{
while(p != NULL && p->num != loc)
{
q = p;
p = p->next;
}
if(p == NULL)
{
q->next = new_node;
new_node->next = NULL;
}
else
{
q->next = new_node;
new_node->next = p;
}
}
}
int main()
{
Link head = NULL;
Link new_node = NULL;
int i;
int loc;
create_link(&head);
for(i = 0; i < 10; i++)
{
//new_node = (Link)malloc(sizeof(Node));
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("please input a number for new_node:\n");
scanf("%d",&new_node->num);
printf("please input a number for insert location:\n");
scanf("%d",&loc);
insert_node_mid(&head,new_node,loc);
display_link(head);
release_link(&head);
display_link(head);
return 0;
}
明日任务
复习链表内容
完成作业