ETC/C, C++
[C, C++] Stack in Array, Lined List
WooGong Peter
2021. 10. 20. 18:14
1. Stack in Array
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10000
#define INF 99999
int stack[SIZE];
int top = -1;
void push(int data) {
if (top == SIZE - 1) {
printf("Stack Overflow !!");
return;
}
stack[++top] = data;
}
int pop() {
if (top == -1) {
printf("Stack Underflow !!");
return -INF;
}
return stack[top--];
}
void show() {
printf("Top Of Stack \n");
for (int i = top; i >= 0; i--) {
printf("%d \n", stack[i]);
}
printf("Bottom Of Stack \n");
}
int main() {
push(2);
push(1);
push(5);
push(7);
push(6);
pop();
push(8);
pop();
push(3);
show();
system("pause");
return 0;
}
2. Stack in Lined List
#include <stdio.h>
#include <stdlib.h>
#define INF 99999
typedef struct {
int data;
struct Node* next;
} Node;
typedef struct {
struct Node *top;
} Stack;
void push(Stack *stack, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = stack->top;
stack->top = node;
}
int pop(Stack *stack) {
if (stack->top == NULL) {
printf("Stack Underflow !!\n");
return -INF;
}
Node* top = (Node*)malloc(sizeof(Node));
top = stack->top;
stack->top = top->next;
int data = top->data;
free(top);
return data;
}
void show(Stack *stack) {
Node* cur = stack->top;
printf("Top Of Stack \n");
while (cur != NULL) {
printf("%d \n", cur->data);
cur = cur->next;
}
printf("Bottom Of Stack \n");
}
int main() {
Stack stack;
stack.top = NULL;
push(&stack, 2);
push(&stack, 1);
push(&stack, 5);
push(&stack, 7);
push(&stack, 6);
pop(&stack);
push(&stack, 8);
pop(&stack);
push(&stack, 3);
show(&stack);
system("pause");
return 0;
}
be the happy Gosu.
woojja ))*
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
반응형