Skip to content

Instantly share code, notes, and snippets.

@fahmifan
Last active May 8, 2019 04:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fahmifan/106dc862e5730a12b0137b7234362311 to your computer and use it in GitHub Desktop.
Save fahmifan/106dc862e5730a12b0137b7234362311 to your computer and use it in GitHub Desktop.
Queue & Stack in cpp
#include <iostream>
using namespace std;
const int maxElmt = 10;
struct Queue {
int data[maxElmt];
int head;
int tail;
};
// create queue
// init head & tail as -1
// -1 means, the array is empty
void createQueue(Queue &q) {
q.head = -1;
q.tail = -1;
}
void push(Queue &q, int elm) {
// kalau queue kosong
if (q.tail == -1) {
// data pertama
q.head = 0;
q.data[0] = elm;
q.tail = 0;
cout << "data99: " << q.data[0] << endl;
// terminate current function
return;
}
// kalau queue udah penuh
if (q.tail == maxElmt-1) {
cout << "puntent, udah penuh" << endl;
// terminate current function
return;
}
// kalau queue berisi
q.tail++;
q.data[q.tail] = elm;
}
void print(Queue q) {
// print queue
cout << "queue: ";
if (q.tail < 0) {
cout << "queue kosong" << endl;
return;
}
for (int i = 0; i <= q.tail; i++) {
cout << q.data[i] << " ";
}
}
int main() {
Queue queue;
createQueue(queue);
// mock
for (int i = 0; i < maxElmt; i++) {
push(queue, i);
}
push(queue, 9999);
print(queue);
}
// Program stack
//
#include <iostream>
using namespace std;
const int maxElm = 10;
struct Stack {
int isi[maxElm];
int top;
};
// inisiasi stack kosong
void createStack(Stack &s) {
// -1 berati stack kosong
// top itu menunjukkan index dari Stack
// stack mulai 0 - maxElm
s.top = -1;
}
// push element into stack start from bottom of stack
// the top var will be increment
void push(Stack &s, int elm) {
// we check if stack is full
// top is zero-indexed
bool isStackFull = s.top == maxElm-1;
if (isStackFull) {
cout << "maaf geus pinuh" << endl;
// terminate current function
return;
}
// increment top, cuz top is -1 in the first place
// kalau stack kosong, s.top = -1;
// ketika dipush, s.top++ maka s.top = 0;
s.top++;
s.isi[s.top] = elm;
}
int main () {
Stack s;
cout << "Init stack " << s.top;
createStack(s);
cout << "top: " << s.top << endl;
cout << "push 99 " << endl;
push(s, 99);
cout << "after push" << endl;
cout << "top: " << s.top << endl;
cout << "top elemt: " << s.isi[s.top] << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment