#ifndef _UTIL_LINKED_STACK_H #define _UTIL_LINKED_STACK_H #include #include #include template struct LinkedStack { T d; struct LinkedStack* next; }; template size_t linked_stack_length(struct LinkedStack* top) { if (!top) return 0; struct LinkedStack* now = top; size_t i = 1; while (now->next) { now = now->next; i += 1; } return i; } template void linked_stack_clear(struct LinkedStack*& top, std::function free_func = std::function()) { if (!top) return; struct LinkedStack* tmp; do { if (free_func) { free_func(top->d); } tmp = top; top = top->next; free(tmp); } while (top); } template void linked_stack_clear(struct LinkedStack*& top, F free_func) { linked_stack_clear(top, std::function(free_func)); } template bool linked_stack_push(struct LinkedStack*& top, T ele) { struct LinkedStack* t = (struct LinkedStack*)malloc(sizeof(struct LinkedStack)); if (!t) { return false; } t->d = ele; t->next = top; top = t; return true; } template bool linked_stack_pop(struct LinkedStack*& top, T& ele) { if (!top) return false; ele = top->d; struct LinkedStack* tmp = top; top = top->next; free(tmp); return true; } template void linked_stack_iter(struct LinkedStack* top, std::function callback, Args... args) { if (!top || !callback) return; struct LinkedStack* now = top; do { callback(now->d, args...); now = now->next; } while (now); } template void linked_stack_iter(struct LinkedStack* top, F callback, Args... args) { linked_stack_iter(top, std::function(callback), args...); } #endif