数据结构-顺序栈基本操作
日常滑水。
//顺序栈 #include<stdio.h> #include<stdlib.h> int Stacksize = 100; int addsize = 10; typedef struct { int *top; int *base; int stacksize; int length; }SqStack; //初始化 int InitStack(SqStack &S) { S.base = (int *)malloc(Stacksize * sizeof(int)); if (!S.base) { printf("栈初始化失败\n"); return 0; } S.top = S.base; S.stacksize = Stacksize; S.length = (*S.top) - 1; } int GetTop(SqStack S) { if (S.top == S.base) { printf("栈为空\n"); return 0; } else { return *(S.top - 1); } } //压栈 int Push(SqStack &S, int e) { if (S.top - S.base >= S.stacksize) { S.base = (int *)realloc(S.base, (S.stacksize + addsize) * sizeof(int)); if (!S.base) { printf("分配空间失败\n"); return 0; } S.top = S.stacksize + S.base; S.stacksize += addsize; } *S.top++ = e; } //弹出 int Pop(SqStack &S) { if (S.base == S.top) { printf("栈为空\n"); return 0; } return *--S.top; } //遍历 void StackTraverse(SqStack &S) { if (S.base == S.top) { printf("栈为空\n"); } else { int *p = S.base; while (p != S.top) { printf("%d", *p); p++; } printf("\n"); } } int main() { SqStack S; InitStack(S); for (int i = 0; i < 4; i++) { int k; scanf_s("%d", &k); Push(S, k); } StackTraverse(S); GetTop(S); Pop(S); StackTraverse(S); return 0; }
北京的天真的冷啊。
===============================分割线==================================
补发一个循环队列
1 #include<stdio.h> 2 #include<stdlib.h> 3 int max = 100; 4 typedef struct { 5 int *base; 6 int rear; 7 int front; 8 }SqQueue; 9 //初始化 10 void InitQueue(SqQueue &Q) { 11 Q.base = (int *)malloc(max * sizeof(int)); 12 if (!Q.base) { 13 printf("空间开辟失败\n"); 14 } 15 else { 16 Q.front = Q.rear = 0; 17 } 18 } 19 unsigned int QueueLength(SqQueue &Q) { 20 return (Q.rear - Q.front); 21 } 22 int EnQueue(SqQueue &Q,int e) { 23 if ((Q.rear + 1) % max == Q.front) { 24 return 0; 25 } 26 Q.base[Q.rear] = e; 27 Q.rear = (Q.rear + 1) % max; 28 } 29 30 void DeQueue(SqQueue &Q) { 31 if (Q.front != Q.rear) { 32 Q.front = (Q.front + 1) % max; 33 } 34 } 35 void TravelQueue(SqQueue &Q) { 36 int i=Q.front; 37 if (Q.front == Q.rear) { 38 printf("循环队列为空\n"); 39 } 40 else { 41 for (i; i <Q.rear; i++) { 42 printf(" %d", Q.base[i]); 43 } 44 printf("\n"); 45 } 46 } 47 int main() { 48 SqQueue Q; 49 InitQueue(Q); 50 for (int i = 0; i < 4; i++) { 51 EnQueue(Q, i); 52 } 53 TravelQueue(Q); 54 DeQueue(Q); 55 TravelQueue(Q); 56 return 0; 57 }

浙公网安备 33010602011771号