C言語シングルチェーンテーブルの実装(単純実装)

2877 ワード

単一チェーンテーブルの削除ループ操作を簡単に実現し、いくつかの機能を実現する必要があります.私は理解しにくいときに絵を描いて論理をはっきりさせ、まず絵を描いて比べてみればいいと思います.
 
// @author:Gong
// @single Linked list
// @  、 、  
#include
#include
/*              ,          */
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!
"); } } 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!
"); } } 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("
"); } 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
",p->data); free(p); print_list(List); while (1); }