堆棧這種數據最鮮明的特色是:後進先出。node
用動態數組實現堆棧:數組
#include "C17.h" #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <assert.h> static STACK_TYPE *stack; //static size_t stack_size static int stack_size; static int top_element = -1; void create_stack(int size) { assert(stack_size == 0); stack_size = size; stack = (STACK_TYPE *)malloc(stack_size * sizeof(STACK_TYPE)); assert(stack != NULL); } void destroy_stack(void) { assert(stack_size > 0); stack_size = 0; free (stack); stack = NULL; } void push (STACK_TYPE value) { assert(! is_full()); top_element += 1; stack[top_element] = value; } void pop(void) { assert(!is_empty()); top_element -= 1; } STACK_TYPE top(void) { assert(!is_empty()); return stack[top_element]; } int is_empty(void) { assert(stack_size > 0); return top_element == -1; } int is_full(void) { assert(stack_size > 0); return top_element == stack_size -1; } int main(void) { int ret,i; create_stack(5); for(i= 0;i<5;i++) { push(i); } for(i= 0;i<5;i++) { ret = top(); printf("dynamic data: %d\n",ret); pop(); } }
鏈式堆棧:spa
#include "C17.h" #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <assert.h> #define FALSE 0 typedef struct STACK_NODE { STACK_TYPE value; struct STACK_NODE *next; }StackNode; static StackNode *stack; //static int stack_size; //static int top_element = -1; void create_stack(int size) { } void destroy_stack(void) { while(!is_empty()) pop(); } void push (STACK_TYPE value) { StackNode *new_node; new_node = (StackNode *)malloc(sizeof(StackNode)); assert(new_node != NULL); new_node->value = value; new_node->next = stack; stack = new_node; } void pop(void) { StackNode *first_node; assert(!is_empty()); first_node =stack; stack = first_node->next; free(first_node); } STACK_TYPE top(void) { assert(!is_empty()); return stack->value; } int is_empty(void) { return stack == NULL; } int is_full(void) { return FALSE; } int main(void) { int ret,i; //create_stack(5); for(i= 0;i<5;i++) { push(i); } for(i= 0;i<5;i++) { ret = top(); printf("dynamic data: %d\n",ret); pop(); } }
隊列:是一種先進先出的結構。須要兩個指針:一個指向隊頭,一個指向隊尾。指針
樹:code
屬性:每一個節點的值比它的左子樹的全部節點的值都要大,但比它的右子樹的全部節點的值都要小。blog
樹的遍歷:前序、中序、後序、層次遍歷。遞歸
前序遍歷:檢查節點的值->遞歸遍歷左子樹和右子樹。隊列
中序遍歷:遍歷左子樹->檢查當前節點的值->遍歷右子樹。。element
後序遍歷:遍歷左右子樹->檢查當前節點的值。io
層次遍歷:逐層檢查樹的節點。處理根節點->處理它的孩子->處理它的孫子。