标签:
Stack
typedef struct{ int *elem; int length; int alloc_length; }stack; void stack_init(stack &s){ s.length = 0; s.alloc_length = 4; s.elem = new int[s.alloc_length]; assert(s.elem != nullptr); } void stack_dispose(stack &s){ delete[] s.elem; } void stack_push(stack &s,int key){ if(s.length == s.alloc_length){ s.alloc_length *= 2; int *temp = s.elem; s.elem = new int[s.alloc_length]; assert(s.elem != nullptr); for(int i=0;i<s.length;i++){ s.elem[i] = temp[i]; } delete[] temp; } s.elem[s.length++] = key; } int stack_pop(stack &s){ assert(s.length > 0); s.length--; return s.elem[s.length]; }
Queue
typedef struct{ int *elem; int size; int alloc_length; }Queue; void queue_init(Queue &s){ s.size = 0; s.alloc_length = 4; s.elem = new int[s.alloc_length]; } void queue_dispose(Queue &s){ delete[] s.elem; } void queue_push(Queue &s, int key){ if(s.size == s.alloc_length){ s.alloc_length *= 2; int *t = s.elem; s.elem = new int[s.alloc_length]; for(int i=0; i<s.size; i++){ s.elem[i] = t[i]; } delete[] t; } s.elem[s.size++] = key; } int queue_pop(Queue &s){ assert(s.size > 0); int key = s.elem[0]; //s.elem = s.elem + 1; //can‘t do this way,if so,original s.elem will be lost,then we can‘t use delete[] s.elem in queue_dispose for(int i=0; i<s.size; i++){ s.elem[i] = s.elem[i+1];//when i=s.size-1,the last element will be ereased } s.size--; return key; }
重复项和索引项
禁止重复项:
特例:栈的元素为整数。
typedef struct{ int *elem;//store elements int *index;//tell if a certain element in stack int size; int alloc_size; }Stack; //新项忽略,easy void stack_push(Stack &s, int key){ if(s.elem[key] == 1){ return; } s.elem[s.size++] = key; s.index[key] = 1; } //旧项遗忘 void stack_push(Stack &s, int key){ if(s.elem[key] == 1){ look_delete(s,key); s.elem[s.size] = key; } s.elem[s.size++] = key; s.index[key] = 1; }
标签:
原文地址:http://www.cnblogs.com/bukekangli/p/4493395.html