单链表的插入:
1、头插
2、尾插
3、中插
4、删除
5、逆序
#include <stdio.h>
struct node
{
int num;
struct node *next;
};
typedef struct node Node;
typedef struct node * Link;
void creat_link(Link *head)
{
*head = NULL;
}
void insert_head_node(Link *newnode, Link *head)
{
(*newnode)->next = *head;
*head = *newnode;
}
void insert_tail_node(Link *newnode, Link *head)
{
if(*head == NULL)
{
(*newnode)->next = NULL;
*head = *newnode;
}
else
{
Link temp = *head;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = *newnode;
(*newnode)->next = NULL;
}
}
int insert_mid_node(Link *newnode, Link *head, int num)
{
if(*head == NULL)
{
return -1;
}
Link temp = *head;
while(temp != NULL)
{
if(temp->num == num)
{
(*newnode)->next = temp->next;
temp->next = *newnode;
break;
}
temp = temp->next;
}
return 0;
}
int delete_node(int num, Link *head)
{
if(*head == NULL)
{
return -1;
}
Link temp = *head;
if(temp->num == num)
{
*head = (*head)->next;
free(temp);
temp = NULL;
return 0;
}
else
{
Link ptr = temp;
temp = temp->next;
while(temp != NULL)
{
if(temp->num == num)
{
ptr->next = temp->next;
free(temp);
temp = NULL;
return 0;
}
ptr = temp;
temp = temp->next;
}
}
}
int reverse_link(Link *head)
{
if(*head == NULL || (*head)->next == NULL)
{
return 0;
}
Link ptr = *head;
Link str = ptr->next;
Link temp = str->next;
while(temp != NULL)
{
str->next = ptr;
ptr = str;
str = temp;
temp = temp->next;
}
str->next = ptr;
(*head)->next = NULL;
*head = str;
}
int display_node(Link *head)
{
if(*head == NULL)
{
return -1;
}
Link temp = *head;
while(temp != NULL)
{
printf("%d\n",temp->num);
temp = temp->next;
}
}
int main()
{
int i;
Link head;
Link newnode;
creat_link(&head);
for(i = 0; i < 10; i++)
{
newnode = (Link)malloc(sizeof(Node));
newnode->num = i + 1;
//insert_head_node(&newnode,&head);
insert_tail_node(&newnode,&head);
}
display_node(&head);
newnode = (Link)malloc(sizeof(Node));
newnode->num = 11;
insert_mid_node(&newnode,&head,5);
display_node(&head);
printf("delete 5:\n");
delete_node(5,&head);
display_node(&head);
return 0;
}