最近做一個低功耗的傳感器探頭項目,是基於TI的MSP430的16位單片機開發,內存才2K。
要做數據結構處理的時候,很不方便,所以手寫了一些鏈表的函數,動態內存分配,動態刪減鏈表,以便達到內存最大程度的利用。
跟普通的鏈表不一樣地方是:
- 該鏈表的長度是動態的,動態的添加和刪除。
- 該鏈表的表頭head是固定的,不可刪除。
頭文件
別忘了malloc的頭文件是#include “stdlib.h”
#include "stdlib.h"
typedef struct 對象
typedef struct Link{
float value;
struct Link *next;
}List;
新建節點
List *creat_node(){
List *node;
node = (List*)malloc(sizeof(List));
if(node==NULL){
printf("malloc fail!\r\n");
}
node->next = NULL;
return node;
}
插入節點
//node3 insert head->node2->node1
//head->node3->node2->node1
void insert_node(List *head, List *node){
node->next = head->next;
head->next = node;
}
新建節點並插入節點
List *insert_creat_node(List *head){
List *node = creat_node();
node->next = head->next;
head->next = node;
return node;
}
刪除節點
void delete(List *head, List *node){
List *l = head;
while(l->next != NULL){
if(l->next == node){
l->next = node->next;
free(node);
break;
}
l = l->next;
}
}
獲取節點長度
int get_length(List *head){
List *l = head->next;
int length = 0;
while(l != NULL){
length++;
l = l->next;
}
return length;
}
獲取鏈表的平均數
float get_average(List *head){
List *l = head->next;
float value = 0;
int length = 0;
while(l != NULL){
value += l->value;
l = l->next;
length++;
}
value /= length;
return value;
}
刪除鏈表中最大值的節點
void delete_max(List *head){
List *l = head->next;
List *max_node = l;
while(l != NULL){
if(l->value > max_node->value){
max_node = l;
}
l = l->next;
}
delete(head, max_node);
}
獲取鏈表中最大值的節點
List *get_max(List *head){
List *l = head->next;
List *max_node = l;
while(l != NULL){
if(l->value > max_node->value){
max_node = l;
}
l = l->next;
}
return max_node;
}
刪除鏈表中最小值的節點
void delete_min(List *head){
List *l = head->next;
List *min_node = l;
while(l != NULL){
if(l->value < min_node->value){
min_node = l;
}
l = l->next;
}
delete(head, min_node);
}
獲取鏈表中最小值的節點
List *get_min(List *head){
List *l = head->next;
List *min_node = l;
while(l != NULL){
if(l->value < min_node->value){
min_node = l;
}
l = l->next;
}
return min_node;
}