88 lines
1.9 KiB
C
88 lines
1.9 KiB
C
#include "stacktest.h"
|
|
#include "alloc.h"
|
|
#include "stack.h"
|
|
#include "testprint.h"
|
|
#include <stdbool.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
stack *random_stack(int size, int maxval) {
|
|
stack* p = create_stack();
|
|
for (int i = 0; i < size; i++) {
|
|
push(rand() % maxval, p);
|
|
}
|
|
return p;
|
|
}
|
|
|
|
stack *tower_stack(int n) {
|
|
stack* p = create_stack();
|
|
for (int i = 0; i < n; i++) {
|
|
push(n - i, p);
|
|
}
|
|
return p;
|
|
}
|
|
|
|
stack *copy_stack(stack *p) {
|
|
stack* p_temp = create_stack();
|
|
stack* p_out = create_stack();
|
|
while (size_stack(p) > 0) {
|
|
push(pop(p), p_temp);
|
|
}
|
|
while (size_stack(p_temp) > 0) {
|
|
int val = pop(p_temp);
|
|
push(val, p);
|
|
push(val, p_out);
|
|
}
|
|
delete_stack(p_temp);
|
|
return p_out;
|
|
}
|
|
|
|
void hanoi(int n) {
|
|
if (n <= 0) return;
|
|
stack *p1 = tower_stack(n);
|
|
stack *p2 = create_stack();
|
|
stack *p3 = create_stack();
|
|
int max = n;
|
|
int *count = 0;
|
|
hanoi_rec(p1, p2, p3, p1, p2, p3, n, max, count);
|
|
return;
|
|
}
|
|
|
|
void hanoi_rec(stack *p1, stack *p2, stack *p3,
|
|
stack *q1, stack *q2, stack *q3,
|
|
int n, int max, int *count) {
|
|
if (n == 0) {
|
|
return;
|
|
};
|
|
hanoi_rec(p1, p3, p2, q1, q2, q3, n-1, max, count);
|
|
push(pop(p1), p3);
|
|
hanoi_rec(p2, p1, p3, q1, q2, q3, n-1, max, count);
|
|
return;
|
|
}
|
|
|
|
void bubble_sort_stack(stack *p) {
|
|
int n = size_stack(p);
|
|
stack *p_aux = create_stack();
|
|
for (int i = 0; i < n; i++) {
|
|
for (int j = 0; j < n - 1; j++) {
|
|
push(pop(p), p_aux);
|
|
}
|
|
for (int j = i; j < n - 1; j++) {
|
|
int a = pop(p);
|
|
int b = pop(p_aux);
|
|
if (a < b) {
|
|
push(a, p);
|
|
push(b, p);
|
|
} else {
|
|
push(b, p);
|
|
push(a, p);
|
|
}
|
|
}
|
|
for (int j = 0; j < i; j++) {
|
|
push(pop(p_aux), p);
|
|
}
|
|
}
|
|
delete_stack(p_aux);
|
|
return;
|
|
}
|