标签:style blog io ar color os 使用 sp 数据
栈是一种先进后出或说是后进先出的数据结构,书中介绍了两种简单实现方法,其中使用链表的是比较方便的方式,而是用数组的方式效率比较高,但是需要初始化的时候指明最大数组元素上限个数。
下面是简单实现:
1.
链表方式
ListStack.cpp
1 /*栈的数组实现*/ 2 #include "iostream" 3 #include "stdlib.h" 4 5 #define log(s); std::cout<<s<<std::endl; 6 7 typedef struct _stack_ 8 { 9 int data; 10 struct _stack_ *pre; 11 }stack; 12 13 void pop(stack *&s) 14 { 15 stack *tmp=nullptr; 16 if (s == nullptr) /*为空栈的时候*/ 17 { 18 log("栈为空,没有数据可以出栈"); 19 return; 20 } 21 tmp = s; 22 s = s->pre; 23 free(tmp); 24 return; 25 } 26 27 void push(stack *&s,int data) 28 { 29 stack *p = (stack *)malloc(sizeof(stack)); 30 p->data = data; 31 p->pre = nullptr; 32 p->pre = s; 33 s = p; 34 return; 35 } 36 37 int top(stack *s) 38 { 39 if (s == nullptr) 40 { 41 std::cout << "栈为空,return "; 42 return -1; 43 } 44 return s->data; 45 } 46 47 void empty(stack *&s) 48 { 49 stack *tmp=nullptr; 50 while (s->pre != nullptr) 51 { 52 tmp = s; 53 s = s->pre; 54 free(tmp); 55 } 56 s = nullptr; 57 } 58 59 int main() 60 { 61 stack *s = nullptr; 62 push(s, 1); 63 push(s, 2); 64 empty(s); 65 log(top(s)); 66 pop(s); 67 system("pause"); 68 return 0; 69 }
2.
数组实现
ArrayStack.cpp
1 /*栈的链表实现*/ 2 #include "iostream" 3 #include "stdlib.h" 4 5 #define minSize 5 6 #define emptyStack -1 7 8 #define log(s); std::cout<<s<<std::endl; 9 10 typedef struct _stack_ 11 { 12 int capacity; 13 int topOfStack; 14 int *Array; 15 }stack; 16 17 stack *createStack(int maxSize) 18 { 19 stack *s; 20 if (maxSize < minSize) 21 { 22 log("Stack size is too small"); 23 } 24 s = (stack *)malloc(sizeof(stack)); 25 s->Array = (int *)malloc(sizeof(int) * maxSize); 26 s->capacity = maxSize; 27 s->topOfStack = emptyStack;/*初始化为空栈*/ 28 return s; 29 } 30 31 int isFull(stack *s)/*检测是否为满栈*/ 32 { 33 if (s == nullptr) 34 { 35 log("the stack has not inital"); 36 return 1; 37 } 38 return s->topOfStack == s->capacity; 39 } 40 41 int isEmpty(stack *s)/*是否为空栈*/ 42 { 43 if (s == nullptr) 44 { 45 log("the stack has not inital"); 46 return 1; 47 } 48 return s->topOfStack == emptyStack; 49 } 50 51 void push(stack *s, int data)/*压栈*/ 52 { 53 if (isFull(s)) 54 { 55 log("Full of Stack"); 56 return; 57 } 58 ++s->topOfStack; 59 s->Array[s->topOfStack] = data; 60 } 61 62 void pop(stack *s)/*弹出栈*/ 63 { 64 if (isEmpty(s)) 65 { 66 log("Out of Stack"); 67 return; 68 } 69 --s->topOfStack; 70 } 71 72 int top(stack *s)/*访问栈顶元素*/ 73 { 74 if (isEmpty(s)) 75 { 76 std::cout << "Out of Stack,Code is "; 77 return emptyStack; 78 } 79 return s->Array[s->topOfStack]; 80 } 81 82 void makeEmpty(stack *&s)/*置空栈*/ 83 { 84 free(s->Array); 85 free(s); 86 s = nullptr; 87 } 88 89 int main(void) 90 { 91 stack *s = createStack(10); 92 push(s, 1); 93 push(s, 2); 94 push(s, 3); 95 log(top(s)); 96 pop(s); 97 log(top(s)); 98 pop(s); 99 log(top(s)); 100 pop(s); 101 log(top(s)); 102 pop(s); 103 makeEmpty(s); 104 pop(s); 105 system("pause"); 106 return 0; 107 }
如果有实现问题望读者不吝指出,谢谢。
以上。
标签:style blog io ar color os 使用 sp 数据
原文地址:http://www.cnblogs.com/lhyz/p/4109557.html