Stack Java

Stack


package stack;
public class StackObject {
private int size;
private int top;
private Object []data;
// method
public StackObject(int n){
top = -1;
size = n;
data = new Object[size];
}
public boolean isFull(){
return top == (size-1) ? true : false;
//if (top == size-1)return true;
//else return false;
}
public boolean isEmpty(){
return top == -1 ? true : false;
//if (top == -1) return true;
//else return false;
}
public void push(Object dt){
if (!isFull()){
data[++top]=dt;
}
}
public Object pop(){
Object hasil=-999;
if (!isEmpty()){
hasil = data[top--];
}
return hasil;
}
   
}


public class Stack {
// Struktur Data
private int size;
private int top;
private int []data;
// method
public Stack(int n){
top = -1;
size = n;
data = new int[size];
}
public boolean isFull(){
return top == (size-1) ? true : false;
//if (top == size-1)return true;
//else return false;
}
public boolean isEmpty(){
return top == -1 ? true : false;
//if (top == -1) return true;
//else return false;
}
public void push(int dt){
if (!isFull()){
data[top++]=dt;
}
}
public int pop(){
int hasil=-999;
if (!isEmpty()){
hasil = data[top--];
}
return hasil;
}
public static void main (String[] args) {
    Stack st = new Stack(3);
st.push(0);
st.push(6);
st.push(7);
while (!st.isEmpty()){
System.out.println(st.pop());
}
//app stack
int nilai = 1234;
Stack s = new Stack(100);
while (nilai != 0){
int sisa = nilai % 2;
s.push(sisa);
nilai = nilai/2;
}
while (!s.isEmpty()){
System.out.print(s.pop());
}
            System.out.println();
    }
}


public class Buku{
private String judul;
private String pengarang;
public Buku(String jdl, String peng){
this.judul = jdl;
this.pengarang = peng;
}
public String toString(){
return String.format("%s %s", this.judul, this.pengarang);
}
}


public class AppStackObject {
public static void main(String[] args) {
//implementasi Stack
StackObject st = new StackObject(3);
st.push(new Double(5));
st.push(new Double(8));
st.push(new Double(7));
while (!st.isEmpty()){
System.out.println(st.pop());
}
StackObject stBuku = new StackObject(3);
stBuku.push(new Buku("Java","Anton"));
stBuku.push(new Buku("Algoritma dan STD","Achmad"));
stBuku.push(new Buku("C++","Budi"));
while (!stBuku.isEmpty()){
System.out.println(stBuku.pop());
}
}
}

Tidak ada komentar:

Posting Komentar