Created
January 2, 2024 02:28
-
-
Save affandes/9e6f22f084f7b1116499725bb1f23f24 to your computer and use it in GitHub Desktop.
Contoh kode program Stack menggunakan Generic untuk berbagai tipe data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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