简单的实现单链表的增删遍历操作,还有一些功能需要实现。我感觉难理解的时候画图来搞清楚逻辑,先画个图比划就行。
// @author:Gong
// @single Linked list
// @ 增、删、遍历
#include<stdio.h>
#include<stdlib.h>
/*从新定义节点的数据域数据类型,以后好修改具体的链表*/
typedef int Data_type;
typedef struct Node* Node_p;
/*定义一个链表的节点结构体,关键有数据域和指针域*/
struct Node{
Data_type data;
struct Node* next;
};
/*创建一个链表,关键是创建一个头节点*/
Node_p create_list(){
Node_p list = (Node_p)malloc(sizeof(struct Node));
list->next = NULL;
return list;
}
/*创建一个链表的节点,也就是开辟一个内存空间存储节点的数据*/
Node_p create_list_node(Data_type data){
Node_p new_node = malloc(sizeof(struct Node));
new_node->data = data;
return new_node;
}
/*在链表的头部增加值*/
void insert_node_by_head(Node_p list, Data_type data){
Node_p new_node = create_list_node(data);
new_node->next = list->next;
list->next = new_node;
}
/*在链表的尾部增加值*/
void insert_node_by_last(Node_p list, Data_type data){
Node_p new_node = create_list_node(data);
Node_p ptr = list->next;
while (ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new_node;
new_node->next = NULL;
}
/*在链表的指定位置增加值*/
void insert_node_by_pos(Node_p list, Data_type data,Data_type pos){
Node_p new_node = create_list_node(data);
Node_p before_node = list;
Node_p after_node=list->next;
while (after_node->data != pos){
before_node = after_node;
after_node = before_node->next;
if (after_node == NULL){
printf("NOT FIND THE POSITION TO INSERT!\n");
}
}
new_node->next = after_node;
before_node->next = new_node;
}
/*在链表的指定参数位置删除,这里只是以值来判断*/
void delete_node_by_pos(Node_p list, Data_type pos){
Node_p before_node=list;
Node_p after_node = list->next;
while (after_node->data != pos){
before_node = after_node;
after_node=after_node->next;
if (after_node == NULL){
printf("Not find the positon to delete node!\n");
}
}
before_node->next = after_node->next;
free(after_node);
}
/*在链表的头部删除*/
Node_p delete_node_by_head(Node_p list){
Node_p temp_node = list->next;
list->next = temp_node->next;
return temp_node;
}
/*打印链表的具体值,遍历操作*/
void print_list(Node_p list){
Node_p ptr = list->next;
while (ptr!= NULL){
printf("%d\t", ptr->data);
ptr = ptr->next;
}
printf("\n");
}
int main(void){
Node_p List = create_list();
insert_node_by_head(List, 1);
insert_node_by_head(List, 2);
insert_node_by_head(List, 3);
insert_node_by_head(List, 4);
insert_node_by_head(List, 5);
insert_node_by_last(List, 6);
insert_node_by_pos(List, 100, 6);
insert_node_by_pos(List, 200, 6);
print_list(List);
delete_node_by_pos(List, 200); // 没有返回被删的节点
print_list(List);
Node_p p= delete_node_by_head(List); // 返回被删的节点
printf("Not be free:%d\n",p->data);
free(p);
print_list(List);
while (1);
}