#include <stdio.h>
#include <stdlib.h>
typedef struct _node
{
int data;
struct _node *next;
}Node;
Node* create_list()
{
Node *head_node = (Node *)malloc(sizeof(Node));
head_node->next = NULL;
return head_node;
}
Node* create_node(int data)
{
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
void insert_node_by_head(Node *head_node, int data)
{
Node *new_node = create_node(data);
new_node->next = head_node->next;
head_node->next = new_node;
}
void insert_node_by_pos(Node *head_node, int insert_data, int data)
{
Node *p = head_node->next;
Node *p_pro = head_node;
if(p == NULL)
{
printf("链表为空 \n");
return;
}
else
{
while (p->data != data)
{
p_pro = p;
p = p->next;
if(p == NULL)
{
printf("未找到数据 \n");
return;
}
}
Node *new_node = create_node(insert_data);
new_node ->next = p;
p_pro->next = new_node;
}
}
void insert_node_by_tail(Node *head_node, int data)
{
Node *p_tail = head_node;
Node *new_node = create_node(data);
while(p_tail->next != NULL)
{
p_tail = p_tail->next;
}
p_tail->next = new_node;
}
void print_list(Node *list)
{
Node *p = list->next;
while (p)
{
printf("%d\t", p->data);
p = p->next;
}
printf("\n");
}
int main(int argc, char const *argv[])
{
printf("list operation \n");
Node *node_list = create_list();
insert_node_by_head(node_list, 1);
printf("数据: \n");
print_list(node_list);
printf("表头插入法: \n");
insert_node_by_head(node_list, 2);
insert_node_by_head(node_list, 4);
print_list(node_list);
printf("指定位置插入法: \n");
insert_node_by_pos(node_list, 3, 2);
print_list(node_list);
printf("表尾插入法: \n");
insert_node_by_tail(node_list, 0);
insert_node_by_tail(node_list, -1);
print_list(node_list);
return 0;
}