#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct _stack{ int* arr; int top, size; }stack; stack createStack(int size) { stack st; st.arr = (int*)malloc(size*sizeof(int)); st.top = -1; st.size = size; return st; } int isEmptyStack(stack &s) { return s.top == -1; } void push(stack &s, int val) { if (s.top == s.size - 1){ int *tmp = s.arr; s.arr = (int*)malloc(2 * s.size*sizeof(int)); memcpy(s.arr, tmp, s.size*sizeof(int)); s.size = s.size * 2; } ++s.top; s.arr[s.top] = val; } int pop(stack &s) { if (isEmptyStack(s)){ printf("stack is empty\n"); exit(-1); } --s.top; return s.arr[s.top + 1]; } typedef struct _queue{ int *arr; int tail, head, size; }queue; queue createQueue(int size) { queue q; q.tail = q.head = 0; q.arr = (int*)malloc(size*sizeof(int)); q.size = size; return q; } void enqueue(queue &q, int val) { if (q.head == (q.tail + 1) % q.size){ int *tmp = q.arr; q.arr = (int*)malloc(2 * q.size*sizeof(int)); memcpy(q.arr, tmp, q.size*sizeof(int)); q.size = 2 * q.size; } q.arr[q.tail] = val; q.tail = (q.tail + 1) % q.size; } int dequeue(queue &q) { if (q.tail == q.head){ printf("queue is empty\n"); exit(-1); } int res = q.arr[q.head]; q.head = (q.head + 1) % q.size; return res; } int main() { int a[] = { 1, 2, 3, 4, 5, 6, 7 }; stack ss = createStack(5); for (int i = 0; i < 7; ++i) push(ss, a[i]); printf("%d\n", ss.size); for (int i = 0; i < 7; ++i) printf("%d\t", pop(ss)); printf("\n"); queue q = createQueue(5); for (int i = 0; i < 5; ++i) enqueue(q, a[i]); dequeue(q); dequeue(q); enqueue(q, 100); enqueue(q,200); for (int i = 0; i <6; ++i) printf("%d\t", dequeue(q)); }
时间: 2024-11-07 08:20:38