Skip to content

Instantly share code, notes, and snippets.

@affandes
Created January 2, 2024 02:28
Show Gist options
  • Save affandes/9e6f22f084f7b1116499725bb1f23f24 to your computer and use it in GitHub Desktop.
Save affandes/9e6f22f084f7b1116499725bb1f23f24 to your computer and use it in GitHub Desktop.
Contoh kode program Stack menggunakan Generic untuk berbagai tipe data
public class Stack<T> {
public T[] data;
public int top;
public Stack(Class<T> c, int n) {
this.data = (T[]) Array.newInstance(c, n);
this.top = 0;
}
public void push(T d) {
if (this.top < this.data.length) {
this.data[this.top] = d;
this.top++;
}
}
public T pop() {
if (this.top > 0) {
this.top--;
return this.data[this.top];
}
return null;
}
public T peek() {
if (this.top > 0) {
return this.data[this.top-1];
}
return null;
}
public boolean empty() {
return this.top == 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment