Anda di halaman 1dari 32

PRAKTIKUM ALGORITMA DAN STRUKTUR DATA

MODUL KE-3

STACK & QUEUE



























LABORATORIUM PEMROGRAMAN
PROGRAM STUDI TEKNIK INFORMATIKA
FAKULTAS TEKNIK
UNIVERSITAS MUHAMMADIYAH MALANG
2011


I. TUJUAN
Mahasiswa mampu :
1. Memahami model penyimpanan data dalam stack dan queue.
2. Memahami model pengaksesan elemen dalam struktur data stack dan queue.
3. Memahami dan mampu menggunakan metode- metode standar di kelas stack dan queue.
4. Membuat ADT Stack dan Queue sendiri baik dalam versi array maupun linked list.

II. ALAT YANG DIGUNAKAN
Peralatan yang digunakan :
1. Perangkat PC yang terinstall Java
2. Editor Java

III. DASAR TEORI
Operasi stack
Stack adalah suatu urutan elemen yang elemennya dapat diambil dan ditambah
hanya pada posisi akhir (top) saja. Contoh dalam kehidupan sehari- hari adalah tumpukan
piring di sebuah restoran yang tumpukannya dapat ditambah pada bagian paling atas dan
jika mengambilnya pun dari bagian paling atas pula.
Ada 2 operasi paling dasar dari stack yang dapat dilakukan, yaitu :
1. Operasi push yaitu operasi menambahkan elemen pada urutan terakhir (paling atas).
2. Operasi pop yaitu operasi mengambil sebuah elemen data pada urutan terakhir dan
menghapus elemen tersebut dari stack.
Sebagai contoh, misalkah ada data sebagai berikut : 1 3 5 6, maka data tersebut dapat
tersimpan dalam bentuk sebagai berikut :

Contoh lain adalah ada sekumpulan perintah stack yaitu push(5), push(7), pop, push(3), pop.
Jika dijalankan, maka yang akan terjadi adalah :

Selain operasi dasar stack (push dan stack), ada lagi operasi lain yang dapat terjadi dalam
stack yaitu :
1. Proses deklarasi yaitu proses pendeklarasian stack.
2. Proses isempty yaitu proses pemeriksaan apakah stack dalam keadaan kosong.
3. Proses isfull yaitu proses pemeriksaan apakah stack telah penuh.
4. Proses inisialisasi yaitu proses pembuatan stack kosong, biasanya dengan pemberian nilai
untuk top.
Representasi stack dalam pemrograman, dapat dilakukan dengan 2 cara yaitu :
1. Representasi stack dengan array
2. Representasi stack dengan single linked list
Sebagai contoh representasi kedua cara tersebut dengan operasi yang dilakukan adalah
push(1), push(2), pop, push(5), push(8), pos. Untuk lebih detail, perhatikan gambar di bawah
ini :
Representasi stack dengan menggunakan array dengan maksimal data 5 adalah




Contoh program menggunakan stack :
class item //atau node/simpul
{
public int data; // data item
public item next; // next node link in list
public item prev; // previous node link in list
public item(int id) // constructor
{
data = id; // initialize data
} // set to null)
public void displayLink() // display ourself
{
System.out.print({ + data + } );
}
} // end class Link
class StackLinkList
{
private item top; // ref to first link on list
private item bottom; // ref to last link on list
public StackLinkList() // constructor
{
top = bottom = null; // no items on list yet
}
public boolean isEmpty() // true if list is empty
{
return (top==null);
}
public void push(int id) //node baru selalu di top
{ // make new link
item newitem = new item(id);
if (top == null) // the first node created
{
top = bottom = newitem; // first > newLink
}
else // the second node and the next node
{
top.next = newitem; //next dr top (awal) diarahkan ke node baru
newitem.prev = top; //prev dr node baru diarahkan ke tail (awal)
top = newitem; //top (baru) diarahkan ke node baru
}
}
public item pop() // delete first item
{ item temp = null;
if (top == null) // stack is empty
System.out.println(Stack is empty);
else if (top == bottom) // stack is only one data
{
temp = top;
top = bottom = null;
}
else // stack has more than one data
{
temp = top; // save reference to link
top = top.prev; // delete it: first>old next
top.next = null;
}
return temp;
}
public void display()
{
item current = bottom; // start from the first data
while(current != null) // until end of list,
{
current.displayLink(); // print data
current = current.next; // move to next link
}
System.out.println();
}
} // end class LinkList
class StackLinkListApp
{
public static void main(String[] args)
{
StackLinkList theStack = new StackLinkList(); // make new list
System.out.println(Initializing Stack);
theStack.push(22); // insert four items
theStack.push(44);
theStack.push(66);
theStack.push(88);
System.out.println(Display Forward :);
theStack.display(); // display list
System.out.println(Delete Stack from Top);
while( !theStack.isEmpty() ) // until its empty,
{
item aLink = theStack.pop(); // delete link
System.out.print(Deleted ); // display it
aLink.displayLink();
System.out.println();
}
theStack.display(); // display list
} // end main()
}


Operasi Queue
Struktur data queue (antrian) dapat diimplementasikan dengan menggunakan array
maupun linked list sebagai penyimpanan datanya. Dalam contoh program berikut ini saya
gunakan double linked list untuk implementasi queue. Secara umum, operasi dalam queue
ada 2 yang utama yaitu enqueue dan dequeue. Enqueue berarti memasukkan item baru ke
dalam antrian. Sedangkan dequeue untuk mengeluarkan item dari antrian. Queue bersifat
FIFO, First In First Out. Item yang pertama kali masuk akan menjadi yang pertama keluar.
Pintu masuk dan pintu keluar queue ada sendiri-sendiri. Berbeda dengan stack yang hanya
ada satu. Item baru akan masuk dari pintu belakang (rear), sedangkan data keluar dari pintu
depan (front). Berikut adalah contoh programnya dengan menngunakan linked list.

class item //atau node/simpul
{
public int data; // data item
public item next; // next node link in list
public item prev; // previous node link in list
public item(int id) // constructor
{
data = id; // initialize data
} // set to null)

public void displayLink() // display ourself
{
System.out.print("{" + data + "} ");
}
} // end class Link
class QueueLinkList
{
private item front; // ref to first link on list
private item rear; // ref to last link on list
public QueueLinkList() // constructor
{
front = rear = null; // no items on list yet
}
public boolean isEmpty() // true if list is empty
{
return (front==null);
}
public void enqueue(int id) //node baru selalu di top
{ // make new link
item newitem = new item(id);
if (front == null) // the first node created
{
front = rear = newitem; // first --> newLink
}
else // the second node and the next node
{
rear.next = newitem; //next dr top (awal) diarahkan
ke node baru
newitem.prev = rear; //prev dr node baru diarahkan
ke tail (awal)
rear = newitem; //top (baru) diarahkan ke node
baru
newitem.next = null;
}
}
public item dequeue() // delete first item
{ item temp = null;
if (front == null) // queue is empty
System.out.println("Queue is empty");
else if (front == rear) // queue is only one
data
{
temp = front;
front = rear = null;
}
else // queue has more than one data
{
temp = front; // save reference to link
front = front.next; // delete it: first-->old next
front.prev = null;
}
return temp;
}
public void display()
{
item current = front; // start from the first data
if (current == null)
System.out.println("The Queue is empty");
else
while(current != null) // until end of list,
{
current.displayLink(); // print data
current = current.next; // move to next link
}
System.out.println("");
}
} // end class LinkList
class QueueLinkListApp
{
public static void main(String[] args)
{
QueueLinkList theQueue = new QueueLinkList(); // make new
list
System.out.println("Inserting queue's items...");
theQueue.enqueue(22); // insert four items
theQueue.display(); // display list
theQueue.enqueue(44);
theQueue.display(); // display list
theQueue.enqueue(66);
theQueue.display(); // display list
theQueue.enqueue(88);
theQueue.display(); // display list
System.out.println("Display Queue :");
theQueue.display(); // display list
System.out.println("Delete Queue from Front...");
while( !theQueue.isEmpty() ) // until it's empty,
{
item aLink = theQueue.dequeue(); // delete link
System.out.print("Deleted "); // display it
aLink.displayLink();
System.out.println("");
theQueue.display(); // display list
System.out.println("");
}
} // end main()
} // end class LinkListApp


IV. PROSEDUR PELAKSANAAN
Prosedur pelaksanaan praktikum adalah sebagai berikut :
1. Mahasiswa mencoba latihan yang ada pada modul praktikum
2. Mahasiswa menganalisa hasil dari program pada latihan yang telah dijalankan
3. Mahasiswa mengerjakan tugas yang diberikan
4. Mahasiswa mendemonstrasikan program yang telah dikerjakan pada dosen/assisten
5. Mahasiswa membuat laporan dari tugas yang telah dikerjakan
6. Upload laporan melalui e- labit.umm.ac.id



V. LATIHAN
Petunjuk :
Tulislah semua program latihan pada editor (Netbeans)
Jika ada error, cari dan benarkan hingga program berhasil di-compile
Jalankan program dan analisa hasilnya untuk memudahkan mengerjakan
tugas praktikum.
Khusus untuk implementasi linked list, buatlah class Node terlebih dahulu. Isi
dari class Node sama seperti class Node yang telah dibuat dipraktikum
sebelumnya (tinggal memodifikasi sedikit disesuaikan dengan kebutuhan
class sekarang).

1. Program : implementasi stack dengan menggunakan array
import java.util.*;

public class StackArray {

int tumpukan[];
int array_size;
int top;

int peekStack(){
return tumpukan[top];
}
void pushStack(int data){
if(isFull()){
System.out.println("Stack penuh!");
tumpukan = resizing(tumpukan);
}
tumpukan[++top]=data;
}

int popStack(){
if(isEmpty())
throw new EmptyStackException();
return tumpukan[top--];
}

int[] resizing(int[] elem){
int[] newArr = new int[2*array_size];
System.arraycopy(element, 0,newArr,0,array_size);
array_size = newArr.length;
return newArr;
}

boolean isEmpty()
{
return (top==-1);
}

boolean isFull()
{
return (top==array_size-1);
}
void inisialisasi(int arrSize)
{
array_size = arrSize;
tumpukan = new int[array_size];
atas = -1;
}


2. Program : implementasi stack dengan menggunakan linked list

import java.util.*;

public class StackLinkedList {

Node head,tail,top;

int peekStack(){
return top.data;
}

void pushStack(Node new){
addLast(baru);
top = tail;
}
void addLast(Node input){
if (is Empty()){
head = input;
tail = input;
}
else
{
tail.next = input;
tail = input;
}
}

int popStack(){
if (isKosong())
throw new EmptyStackException();
int tampungData = top.data;
removeLast();
top=tail;
return tampungData;
}
void removeLast(){
Node temp = head;
if (tail == kepala){
head = tail = null;
}
else {
while (temp.next != tail){
temp = temp.next;
}
temp.next = null;
tail = temp;
temp = null;
}
}

boolean isEmpty()
{
return (top==null);
}

void inisialisasi(){
head = tail = atas= null;
}

public static void main(String[] args)
{

}
}

3. Program : implementasi queue dengan menggunakan array
public class QueueArray {
int antrian[];
int array_size;
int front,rear;
int jumlah_item;
void inisialisasi(int arrSize)
{
array_size = arrSize;
antrian = new int[array_size];
jumlah_item = 0;
front=0;
rear=-1;
}
void enqueue(int data){
if(isFull()){
System.out.println("Queue penuh!");
antrian = resizing(antrian);
}
//jumlah_item++;
antrian[++rear]=data;
}
void dequeue(){
if(!is Empty())
{
for(int i=0; i<jumlah_item-1;i++)
antrian[i]=antrian[i+1];
//jumlah_item--;
rear--;
}
else
{
System.out.println("Queue Kosong!");

}
}
int peekQueue(){
return antrian[front];
}

int[] resizing(int[] element){
int[] newArr = new int[2*array_size];
System.arraycopy(element, 0,newArr,0,array_size);
array_size = newArr.length;
return newArr;
}
boolean isFull()
{
return (jumlah_item==array_size-1);
}

boolean isEmpty()
{
return (jumlah_item==0);
}
}

4. Program : implementasi queue dengan menggunakan linked list

public class QueueLinkedList {
Node head,tail,front, rear;
int jumlah_item;

int peekQueue(){
return front.data;
}

void enqueue(Node baru){
//addLast(baru);
rear = tail;
jumlah_item++;
}

void addLast(Node input){
if (is Empty()){
head = input;
tail = input;
}
else
{
tail.next = input;
tail = input;
}
}

void dequeue(){
if (!isKosong())
{
//removeFirst();
front=head;
jumlah_item--;
}
else
{
System.out.println("Queue Kosong!");
}
}

void removeFirst(){
Node temp = head;
if (head == tail)
head = tail = rear=null;
else
{
temp = temp.next;
head = temp;
temp = null;
}
}

boolean isEmpty()
{
return (jumlah_item==0);
}

void inisialisasi(){
head = tail = front=rear= null;
jumlah_item=0;
}
}


5. Program : class stack yang telah disediakan java
import java.util.*;

public class StackJava {
public static void main(String[] args)
{
Stack tumpukan = new Stack();
tumpukan.push("Data Satu");
tumpukan.push("Data Dua");
tumpukan.push("Data Tiga");
System.out.print ln("Melihat data paling atas = " + tumpukan.peek());

for(int i=tumpukan.size()-1;i>=0;i--)
{
System.out.println(tumpukan.elementAt(i));
}

System.out.print ln("Ambil data dari larik = " + tumpukan.pop());

tumpukan.push(1234);
tumpukan.push(5678);

for(int i=tumpukan.size()-1;i>=0;i--)
{
System.out.println(tumpukan.elementAt(i));
}
}
}

Soal Bonus!
1. (1 orang) Buatlah flowchart dan program untuk menampikan data pada single linked list dari
belakang ke depan. (manfaatkan konsep LIFO pada stack)


VI. TUGAS

2. (2 orang) Impelementasikan class stack yang ada pada latihan diatas untuk membuat program
konversi bilangan desimal ke bilangan biner, dengan algoritma sebagai berikut :
Konversi Bilangan Desimal ke Biner
1. Ambil sisa pembagian variable bilangan dengan angka 2, kemudian simpan dalam
variable sisa. Kemudian simpan isi variable sisa ke dalam stack.
2. Bagi variable bilangan dengan angka 2.
3. Ulangi langkah 1 dan 2 selama bilangan tidak 0. Jika variable bilangan telah bernilai 0
maka lanjutkan ke langkah 4,
4. Lakukan perulangan untuk langkah 5 dan 6 selama stack masih mempunyai isi (tidak
kosong).
5. ambil (pop) nilai yang ada di stack simpan di variable data.
6. Tulis isi variable data ke layar .
7. Selesai.
Contoh tampilan program konversi desimla ke biner :
Input : 25
Hasil biner : 11001

3. (2 orang) Buatlah program untuk mengubah notasi infix ke postfix dengan menggunakan
algoritma dibawah ini :
1. Push tanda ( ke stack dan tambahkan tanda ) di sentinel di Q.
2. Scan Q dari kiri ke kanan, kemudian ulangi langkah c s.d f untuk setiap elemen Q sampai
stack Q kosong.
3. Jika yang discan adalah operand, maka tambahkan ke P
4. Jika yang discan adalah ( maka push ke stack
5. Jika yang discan adalah ) maka pop isi stack sampai ditemukan tanda (,
6. kemudian tambahkan ke P sedangkan tanda ( tidak disertakan ke P.
7. Jika yang discan adalah operator, maka :
- Jika elemen paling atas dari stack adalah operator yang mempunyai tingkatan sama atau
lebih tinggi dari operator yang discan, maka pop operator tersebut dan tambahkan ke P.
8. Push operator tersebut ke stack.
9. Keluar

4. (1 orang) Buatlah flowchart dan program implementasi dari penggabungan konsep stack dan
queue. Program berupa menu untuk memilih operasi yang dilakukan pada stack maupun queue.
Program akan berakhir jika user memilih menu selesai.
Aturan :
1. Jika operasi remove, maka akan menghapus item yang ada pada stack maupun queue
(sesuai dengan konsep masing- masing struktur data tersebut).
2. Jika operasi add, maka akan menambahkan item pada stack maupun linked list.
3. Jika operasi peek, maka akan menampilkan 1 item pada masing- masing struktur data
(stack dan queue).
4. Jika operasi peer to peer, maka akan dilakukan pertukaran data pada stack dan queue.
Item yang ditunjuk oleh top pada stack akan menempati posisi item yang ditunjuk oleh
front pada queue. Sebaliknya, item yang ditunjuk oleh front pada queue akan menempati
posisi item yang ditunjuk oleh top pada stack. (Gunakan Array untuk impelementasi
program)
Contoh tampilan program :
Program Penggabungan Konsep Stack dan Queue
====================================
Menu Pilihan Operasi:
1. Add
2. Remove
3. Peek
4. Peer to Peer
5. Selesai
Masukkan Pilihan : 1
Masukkan item : A
Masukkan Pilihan : 1
Masukkan item : B
Masukkan Pilihan : 1
Masukkan item : C
Masukkan Pilihan : 4
Sebelum :
Queue : A B C
Stack : A B C
Setelah ditukar :
Queue : C B C
Stack : A B A
Masukkan Pilihan : 3
Queue : C
Stack : A
Masukkan Pilihan : 2
Remove Queue : C
Remove Stack : A
Masukkan Pilihan : 5
=============================

VII. HASIL PRAKTIKUM
Soal 2
Sintak
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author noSpiritnoLife
*/
import javax.swing.*;
import java.util.*;

public class destobin {
int b;
int tumpukan[];
int array_size;
int top;
private int rear;
private int[] antrian;
private int jumlah_item;

int peekStack(){
return tumpukan[top];
}

void pushStack(int data){
if(isFull()){
System.out.println("Stack penuh!");
tumpukan = resizing(tumpukan);
}
tumpukan[++top]=data;
}


int dequeue1(){
if(isEmpty())
throw new EmptyStackException();
return tumpukan[top--];
}

void enqueue(int data){
if(isFull()){
System.out.println("Queue penuh!");
antrian = resizing(antrian);
}
//jumlah_item++;
antrian[++rear]=data;
}
void dequeue(){
if(!isEmpty())

{
for(int i=0;i<jumlah_item-1;i++)
antrian[i]=antrian[i+1];
//jumlah_item--;
rear--;
}
else
{
System.out.println("Queue Kosong!");

}
}

int[] resizing(int[] elem){
int[] newArr = new int[2*array_size];
System.arraycopy(elem, 0,newArr,0,array_size);
array_size = newArr.length;
return newArr;
}

boolean isEmpty(){
return (top==-1);
}

boolean isFull(){
return (top==array_size-1);
}

void inisialisasi(int arrSize){
array_size = arrSize;
tumpukan = new int[array_size];
top = -1;
}

void DesToBin(int bilangan){ //method utama yang digunakan
int sisa;


do{
sisa = bilangan%2;
pushStack(sisa);
bilangan = bilangan/2;
}while(bilangan!=0);

while(!isEmpty()){
int data = dequeue1();
System.out.print(data);
}
System.out.println();


}

public static void main(String[] args) {
destobin obj = new destobin();
Scanner input = new Scanner(System.in);
obj.inisialisasi(20);//inisialisasi ukuran array yang digunakan untuk menyimpan
StackArray
boolean ulang = true;

while(ulang){
System.out.println("Konversi Bilangan Desimal ke Biner !");
try{
// JOptionPane.showInputDialog(" masuk ");

System.out.print("Masukkan angka: ");
int a = input.nextInt();
System.out.print("Hasil biner: ");
obj.DesToBin(a); //pemanggilan method merubah biner ke desimal
}catch(InputMismatchException exeption){
ulang=false;
System.out.println("maaf, inputan angka saja");
}
}
}
}








Soal 3
Sintak
Public class InfixToPostfix extends Stack{

String Q , P = "";
char tanda[] = {'-','+','/','*','^','(',')'};

public int cekKarakter(char karakter){
int value = 0, i;

for (i = 0; i < tanda.length; i++) {
if (karakter == tanda[i]) {
value = 1;break; // karakter sama dengan operator
}

}
return value;
}

public int cekOperator(char opr){

int value = 0;

for (int i = 0; i < tanda.length; i++) {
if (opr == tanda[i]) {

value = i;
if (value==2) {
value =1;
}else if(value ==4){
value =3;
}
break;
}
}
return value;
}

public void ItoP(){

Q+=")";
super.push(new Nodes('(' ));

for (int i = 0; i < Q.length(); i++) {

int value = cekKarakter(Q.charAt(i));

if (value == 0) {
P+=Q.charAt(i); // menambahkan operand ke string P
}
else if(value==1){
if (super.top.data == '(' && Q.charAt(i) !=')') {
super.push(new Nodes(Q.charAt(i)));
}
else if(super.top.data != '(' ){
if (Q.charAt(i) ==' (') {
super.push(new Nodes(Q.charAt(i)));
}
else if(Q.charAt(i)!='(' && Q.charAt(i) !=')' ){
int opr1 = cekOperator(Q.charAt(i));

int opr2 = cekOperator(super.top.data);


if (opr2>=opr1) {
P+=super.pop();
super.push(new Nodes(Q.charAt(i)));
}
else if(opr1>opr2){
super.push(new Nodes(Q.charAt(i)));
}
}
else if(Q.charAt(i)==' )'){
while(super.top.data != '(' ){
P+=super.pop();
}
super.pop();
}
//cek tingkatan karakter operator

}

}
}

System.out.println(P);
super.showFromBack();
}

public static void main(String[] args) {
InfixToPostfix obj = new InfixToPostfix();

System.out.print("Lebokno Infix e : ");
obj.Q = new java.util.Scanner(System.in).nextLine();

System.out.print("Postfix e ngene iki : ");
obj.ItoP();


}

}

class Nodes{

char data;

Nodes pointer;

Nodes() {}
Nodes(char data)
{
this.data = data;
}
Nodes(char data, Nodes pointer)
{
this.data = data;
this.pointer = pointer;
}

}

class LinkedListed{

Nodes head, tail;
int size=0;

void inisialisasi(){

head=tail=null;
}

boolean isEmpty(){
boolean value;
if (size == 0) {
value = true;
}else{
value = false;
}

return value;
}

int size(){
return size;
}


void addLast(Nodes input){
if (isEmpty()==true) {
head=tail=input;

}else{
tail.pointer=input;
tail = input;

}
size++;
}


public void removeLast(){

Nodes temp = head;

if (isEmpty() == false) {
if (head==tail) {
head=null;
tail=null;
}else{
while(temp.pointer!=tail){
temp = temp.pointer;
}

temp.pointer = null;
tail = temp;
temp=null;
}
size--;
}else{
System.out.println("no Node");
}

}

}

class Stack extends LinkedListed{ //class Stack

Nodes top;
@Override
public void inisialisasi(){
top = super.head= super.tail=null;

}

public void push(Nodes newNode){
super.addLast(newNode);
top=super.tail;

}

public char pop(){
char tmpVal = top.data;
if (super.isEmpty()) {
tmpVal=' ';
}else{
super.removeLast();
top = tail;
//System.out.println(tmpVal);
//System.out.println(top.pointer);
}


return tmpVal;
}

public char peek(){

return top.data;
}

public void showFromBack(){
for (int i = super.size; i >0; i--) {
System.out.print(pop());
}
System.out.println ("Lek pengen mbaleni,langsung pinek (shift + f6) ");

}
}


Screenshort



Flowchat soal 4.
Part 1
Mulai
Input:1,2,3,4,5
Input!=5
Y
Input =1
And
N
Input = 2
Input =3
Input =4
N
N
N
N
1
2
3
4
Y
Y
Y
Y
e

Part 2.
1
pilihan 1
Inputan ==Z
Input Data
Input !=Z
Panggil Method
pushStack
Inputan ==Z
Input Data
Input !=Z
Panggil Method
enqueue
e
System.out.print("Melanjutk
an pengisisan Queque/
inputan Z tidak
dimasukkan");
System.out.print("Keluar...
penginputan data/inputan
Z tidak dimasukkan");
Part 3
For i=0;i<top+1
i++
System.out.print("
"+ tumpukan[i]);
3
e
Panggil method
peekStack
Panggil method
peekQueque
For i=0;i<rear+1
i++
System.out.print("
"+ antrian[i]);
Part 4
For a=0;a<rear+1
a++
pushStack_temp
(antrian[a]);
4
b
Panggil method
peekStack
For c=top;c>=0
C - -
Panggil method
peekQueque
Panggil method
PeerToPeer
Jumla_item !=0
Pangil method
dequeue()
Jumlah_item - -
enqueue(tumpukan[c])
Top+1 !=0
Pangil method
popStack();
Top--
e
For x=top_temp;x>=0
x--
pushStack(tumpukan_temp[x])
top_temp+1!=0
popStack_temp();
Top_temp--
b
Sintak soal 4.
package Prakt ikum3;
import java.util.*;
public class Soal4 {
//variable stack
char tumpukan[];
int top;
int arry_size;

//variable queque
char antrian[];
int array_size_que;
int front,rear;
int jumlah_item;

//variable stack temp;
char tumpukan_temp[];
int top_temp;
int arry_size_temp;

//blog stack temp
//nilai awal stack temp
void nilaiAwal_temp(int arrySize){
arry_size_temp =arrySize;
tumpukan_temp =new char[arry_size_temp];
top_temp = -1;
}
boolean kosong_temp(){
return (top_temp==-1);
}

int popStack_temp(){
if(kosong_temp())
throw new EmptyStackException();
return tumpukan_temp[top_temp--];
}

boolean penuh_temp(){
return (top_temp == arry_size_temp - 1);
}

char[] resizing_temp(char[] element){
char[] newArr = new char[2*element.length];
System.arraycopy(element, 0, newArr,0,arry_size_temp);
arry_size_temp = newArr.length;
return newArr;
}

void pushStack_temp(char data){
if(penuh_temp()){
System.out.println("Stack penuh!System melakukkan pelebaran tempat");
tumpukan_temp = resizing_temp(tumpukan_temp);
}
tumpukan_temp[++top_temp]=data;
}
void peekStack_temp(){
System.out.print("Data Stack Temp : ");
for(int i=0; i<top_temp+1;i++){
System.out.print(" "+ tumpukan_temp[i]);
}
System.out.println("");
}


//Blog Stack
void nilaiAwal(int arrySize){
arry_size =arrySize;
tumpukan =new char[arry_size];
top = -1;
}

boolean kosong(){
return (top==-1);
}

boolean penuh(){
return (top == arry_size - 1);
}

int popStack(){
if(kosong())
throw new EmptyStackException();
return tumpukan[top--];

}

char[] resizing(char[] element){
char[] newArr = new char[2*element.length];
System.arraycopy(element, 0, newArr,0,arry_size);
arry_size = newArr.length;
return newArr;
}
void pushStack(char data){
if(penuh()){
System.out.println("Stack penuh!System melakukkan pelebaran tempat");
tumpukan = resizing(tumpukan);
}
tumpukan[++top]=data;
}

void peekStack(){
System.out.print("Data Stack : ");
for(int i=0; i<top+1; i++){
System.out.print(" "+ tumpukan[i]);
}
System.out.println("");
}
// Blog Queque
boolean kosongque(){
return(jumlah_item==0);
}
boolean penuh_que(){
return(jumlah_item==array_size_que-1);
}
void niliaAwal_que(int arrySize){
array_size_que = arrySize;
antrian = new char[array_size_que];
jumlah_item =0 ;
front = 0;
rear=-1;
}
char[] resizing_que(char[] element){
char[] newArr_que = new char[2*element.length];
System.arraycopy(element, 0, newArr_que,0,array_size_que);
array_size_que = newArr_que.length;
return newArr_que;
}
void enqueue(char dt){
if(penuh_que()){
System.out.println("Queue penuh");
antrian = resizing_que(antrian);
}
jumlah_item++;
antrian[++rear]= dt;
}
void peekQueue(){
System.out.print("Data Queque : ");
for (int i=0;i<rear+1;i++){
System.out.print(" "+antrian[i]);
}
System.out.print ln("");
}
int dequeue(){
if(!kosongque()){
int temp = antrian[front];
for(int i=0;i<jumlah_item; i++)
antrian[i] =antrian[i+1];
rear--;
jumlah_item--;
return temp;
}else{
System.out.println("Queue kosong! ");
return rear;
}
}
void PeerToPeer(){
//pidah ke temp stack
for(int a=0;a<rear+1;a++){
pushStack_temp(antrian[a]);
}

//hapus antrian
while(jumlah_item!=0){
dequeue();
}

//mempindah stack
for(int c=top;c>=0;c--){
enqueue(tumpukan[c]);
}

//hapus stack
while(top+1!=0){
popStack();
}

//dari temp ke stack
for(int x=top_temp; x>=0; x--){
pushStack(tumpukan_temp[x]);
}

//membersihkan temp
while(top_temp+1!=0){
popStack_temp();
}

}
public static void main(String[] args){
Soal4 ob = new Soal4();
ob.nilaiAwal(5);
ob.niliaAwal_que(5);
ob.nilaiAwal_temp(5);
Scanner ad = new Scanner(System.in);

int pil=0;
do{
System.out.println("Masukkan pillihan Anda :");
System.out.println("1. Add");
System.out.println("2. Remove");
System.out.println("3. Peek");
System.out.println("4. Peer to Pear");
System.out.println("5. Selesai");
System.out.print("Masukkan input : "); int p = ad.next Int();

if (p==1){
char pil1;
char pil2;
do{
//jika ikin berhenti ketikkan 0
System.out.print("Masukkan Item Stack : ");String in =ad.next();
if(in.charAt(0)=='Z'){
System.out.print("Melanjutkan pengisisan Queque/inputan Z tidak dimasukkan");
}else{
ob.pushStack(in.charAt(0));
}
pil1=(in.charAt(0));
}while(pil1!='Z');
System.out.println("\n");
do{
//jika ikin berhenti ketikkan 0
System.out.print("Masukkan Item Queque : ");String in2 =ad.next ();
if(in2.charAt(0)=='Z'){
System.out.print("Keluar...penginputan data/inputan Z tidak dimasukkan");
}else{
ob.enqueue(in2.charAt(0));
}
pil2=(in2.charAt(0));
}while(pil2!='Z');
System.out.println("\n");
}else if (p==2){
if(ob.jumlah_item!=0){
ob.popStack();
ob.dequeue();
}else{
System.out.println("Queue dan Stack!\n");
}
}else if(p==3){
System.out.println("\nData sebelum dirubah!");
ob.peekStack();
ob.peekQueue();
System.out.println("\n");
}else if(p==4){
System.out.println("\nData sebelum dirubah!");
ob.peekStack();
ob.peekQueue();
System.out.println("\nData setelah dirubah!");
ob.PeerToPeer();
ob.peekStack();
ob.peekQueue();
System.out.println("\n");
}
pil=p;
}while(pil!=5);
}
}

Screenshort soal 4.
Add


Remove
Data sebelum di hapus.



Data setelah di hapus.untuk stack penghapusan data menggunakan prinsip LIFO untuk
Queque menggunkan prinsip FIFO



PeekStack dan PeakQue
Melihat data yang telah dimasukkan.


PeerToPeer


VII. KESIMPULAN

Perbedaan antara stack dan queque adalah mengunakan prinsip FIFO dan LIFO
yang mana sudah dijelaskan di dalam landasan teori. Didalam stack terdapat beberapa
oprasi di antaranya adalah pushStack digunakan untuk menambah data dan popStak
digunakan untuk penghapusan data. Sedangkan oprasi yang terdapat pada queque adalah
enqueque digunakan untuk untuk memasukkan data sedangkan dequeque digunakan
untuk penghapusan data.

Anda mungkin juga menyukai