Jumat, 15 November 2013

Tugas Praktikum Sistem Basis Data Bab III

1. Buat table copy_mahasiswa_3digitnimterakhir minimal 5 kolom
2. Tambahkan baris nim ipk. tmbah 2 baris bebas
    - 105060800111092, jono, 3.7
    - 105060800111093, jini, 2.7
    - 105060800111098, junu, 3.4

     perlihtkan data keseluruhan

3. Ubah nama jono jadi marko
4. Ubah ipk menjadi 4.0 nim depannya 1050
5. Delete salah satu baris bebas
6. Hapus seluruh barisnya
7. Lihat datanya

Jawaban :
* Quwery 
Screenshot
No comments

Tugas Praktikum Sistem Basis Data Bab II

1. Buat tabel pada siakaddb dengan nama tabel tabelku3digitnimterakhir dengan kolom biodata
    kalian min(10) kolom
2. Tampilkan 6 kolom dari tabel yang telah dibuat
3. Tampilkan keseluruhan dari tabel yang dibuat
4. Tampilkan nim, alamat, kode_pos,K_kota,K_propinsi, dan k_negara dari tabel mhs_kota
    yang telah dibuat kemarin.

Jawaban :
Quwery
Screenshot

No comments

Kamis, 18 Juli 2013

KONSEP SISTEM BASIS DATA

Sistem Basis Data adalah suatu sistem menyusun dan mengelola record-record menggunakan computer untuk menyimpan atau  merekam serta memelihara data operasional lengkap sebuah organisasi/perusahaan sehingga mampu menyediakan informasi yang optimal yang diperlukan pemakai untuk proses mengambil keputusan. Salah satu cara menyajikan datauntuk mempermudah modifikasi adalah dengan cara pemodelan data. Model yang akan dipergunakan pada pelatihan ini adalah Entity Relationship Model. 

Model Entity Relationship adalah representasi logika dari data pada suatu organisasi atau area bisnis tertentu dengan menggunakan Entity dan Relationship. 

Entity/Entitas 
  • Aadalah obyek di dunia nyata yang dapat dibedakan dari obyek lain.
  • Entity Set/Kumpulan Entity  adalah kumpulan dari entitas sejenis/dalam tipe sama.
  • Entity set dapat berupa:

ü  Obyek fisik : rumah,kendaraan, pegawai
ü  Obyek abstrak : konsep politik, pekerjaan, rencana, dll.

  •        Simbol yang digunakan untuk entity adalah persegi panjang.
  •          Tipe entitas :

ü  Entitas Kuat yaitu entitas mandiri yang keberadaannya tidak bergantung pada keberadaan entitas lain
ü  Entitas Lemah/Weak Entity yaitu entitas yang keberadaannya bergantung pada keberadaan entitas lain
ü  Entitas Assosiatif adalah entitas yang terbentuk dari suatu relasi, bias terjadi jika :
o   Relasi yang merekatkan dua entitas bersifat banyak ke banyak
o   Biasanya berasal dari suatu relasi dimana relasi itu memiliki makna mandiri bagi pengguna
No comments

Rabu, 22 Mei 2013

Graph


import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.StringTokenizer;

import weiss.util.Iterator;
import weiss.util.Collection;
import weiss.util.List;
import weiss.util.Queue;
import weiss.util.Map;
import weiss.util.LinkedList;
import weiss.util.HashMap;
import weiss.util.NoSuchElementException;
import weiss.util.PriorityQueue;

import weiss.nonstandard.PairingHeap;

// Used to signal violations of preconditions for
// various shortest path algorithms.
class GraphException extends RuntimeException
{
    public GraphException( String name )
    {
        super( name );
    }
}

// Represents an edge in the graph.
class Edge
{
    public Vertex     dest;   // Second vertex in Edge
    public double     cost;   // Edge cost
    
    public Edge( Vertex d, double c )
    {
        dest = d;
        cost = c;
    }
}

// Represents an entry in the priority queue for Dijkstra's algorithm.
class Path implements Comparable<Path>
{
    public Vertex     dest;   // w
    public double     cost;   // d(w)
    
    public Path( Vertex d, double c )
    {
        dest = d;
        cost = c;
    }
    
    public int compareTo( Path rhs )
    {
        double otherCost = rhs.cost;
        
        return cost < otherCost ? -1 : cost > otherCost ? 1 : 0;
    }
}

// Represents a vertex in the graph.
class Vertex
{
    public String     name;   // Vertex name
    public List<Edge> adj;    // Adjacent vertices
    public double     dist;   // Cost
    public Vertex     prev;   // Previous vertex on shortest path
    public int        scratch;// Extra variable used in algorithm

    public Vertex( String nm )
      { name = nm; adj = new LinkedList<Edge>( ); reset( ); }

    public void reset( )
      { dist = Graph.INFINITY; prev = null; pos = null; scratch = 0; }    
      
    public PairingHeap.Position<Path> pos;  // Used for dijkstra2 (Chapter 23)
}

// Graph class: evaluate shortest paths.
//
// CONSTRUCTION: with no parameters.
//
// ******************PUBLIC OPERATIONS**********************
// void addEdge( String v, String w, double cvw )
//                              --> Add additional edge
// void printPath( String w )   --> Print path after alg is run
// void unweighted( String s )  --> Single-source unweighted
// void dijkstra( String s )    --> Single-source weighted
// void negative( String s )    --> Single-source negative weighted
// void acyclic( String s )     --> Single-source acyclic
// ******************ERRORS*********************************
// Some error checking is performed to make sure graph is ok,
// and to make sure graph satisfies properties needed by each
// algorithm.  Exceptions are thrown if errors are detected.

public class Graph
{
    public static final double INFINITY = Double.MAX_VALUE;
    private Map<String,Vertex> vertexMap = new HashMap<String,Vertex>( );

    /**
     * Add a new edge to the graph.
     */
    public void addEdge( String sourceName, String destName, double cost )
    {
        Vertex v = getVertex( sourceName );
        Vertex w = getVertex( destName );
        v.adj.add( new Edge( w, cost ) );
    }

    /**
     * Driver routine to handle unreachables and print total cost.
     * It calls recursive routine to print shortest path to
     * destNode after a shortest path algorithm has run.
     */
    public void printPath( String destName )
    {
        Vertex w = vertexMap.get( destName );
        if( w == null )
            throw new NoSuchElementException( "Destination vertex not found" );
        else if( w.dist == INFINITY )
            System.out.println( destName + " is unreachable" );
        else
        {
            System.out.print( "(Cost is: " + w.dist + ") " );
            printPath( w );
            System.out.println( );
        }
    }

    /**
     * If vertexName is not present, add it to vertexMap.
     * In either case, return the Vertex.
     */
    private Vertex getVertex( String vertexName )
    {
        Vertex v = vertexMap.get( vertexName );
        if( v == null )
        {
            v = new Vertex( vertexName );
            vertexMap.put( vertexName, v );
        }
        return v;
    }

    /**
     * Recursive routine to print shortest path to dest
     * after running shortest path algorithm. The path
     * is known to exist.
     */
    private void printPath( Vertex dest )
    {
        if( dest.prev != null )
        {
            printPath( dest.prev );
            System.out.print( " to " );
        }
        System.out.print( dest.name );
    }
    
    /**
     * Initializes the vertex output info prior to running
     * any shortest path algorithm.
     */
    private void clearAll( )
    {
        for( Vertex v : vertexMap.values( ) )
            v.reset( );
    }

    /**
     * Single-source unweighted shortest-path algorithm.
     */
    public void unweighted( String startName )
    {
        clearAll( ); 

        Vertex start = vertexMap.get( startName );
        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        Queue<Vertex> q = new LinkedList<Vertex>( );
        q.add( start ); start.dist = 0;

        while( !q.isEmpty( ) )
        {
            Vertex v = q.remove( );

            for( Edge e : v.adj )
            {
                Vertex w = e.dest;
                if( w.dist == INFINITY )
                {
                    w.dist = v.dist + 1;
                    w.prev = v;
                    q.add( w );
                }
            }
        }
    }

    /**
     * Single-source weighted shortest-path algorithm.
     */
    public void dijkstra( String startName )
    {
        PriorityQueue<Path> pq = new PriorityQueue<Path>( );

        Vertex start = vertexMap.get( startName );
        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        clearAll( );
        pq.add( new Path( start, 0 ) ); start.dist = 0;
        
        int nodesSeen = 0;
        while( !pq.isEmpty( ) && nodesSeen < vertexMap.size( ) )
        {
            Path vrec = pq.remove( );
            Vertex v = vrec.dest;
            if( v.scratch != 0 )  // already processed v
                continue;
                
            v.scratch = 1;
            nodesSeen++;

            for( Edge e : v.adj )
            {
                Vertex w = e.dest;
                double cvw = e.cost;
                
                if( cvw < 0 )
                    throw new GraphException( "Graph has negative edges" );
                    
                if( w.dist > v.dist + cvw )
                {
                    w.dist = v.dist +cvw;
                    w.prev = v;
                    pq.add( new Path( w, w.dist ) );
                }
            }
        }
    }

    /**
     * Single-source weighted shortest-path algorithm using pairing heaps.
     */
    public void dijkstra2( String startName )
    {
        PairingHeap<Path> pq = new PairingHeap<Path>( );

        Vertex start = vertexMap.get( startName );
        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        clearAll( );
        start.pos = pq.insert( new Path( start, 0 ) ); start.dist = 0;

        while ( !pq.isEmpty( ) )
        {
            Path vrec = pq.deleteMin( );
            Vertex v = vrec.dest;
                
            for( Edge e : v.adj )
            {
                Vertex w = e.dest;
                double cvw = e.cost;
                
                if( cvw < 0 )
                    throw new GraphException( "Graph has negative edges" );
                    
                if( w.dist > v.dist + cvw )
                {
                    w.dist = v.dist + cvw;
                    w.prev = v;
                    
                    Path newVal = new Path( w, w.dist );                    
                    if( w.pos == null )
                        w.pos = pq.insert( newVal );
                    else
                        pq.decreaseKey( w.pos, newVal ); 
                }
            }
        }
    }

    /**
     * Single-source negative-weighted shortest-path algorithm.
     */
    public void negative( String startName )
    {
        clearAll( ); 

        Vertex start = vertexMap.get( startName );
        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        Queue<Vertex> q = new LinkedList<Vertex>( );
        q.add( start ); start.dist = 0; start.scratch++;

        while( !q.isEmpty( ) )
        {
            Vertex v = q.remove( );
            if( v.scratch++ > 2 * vertexMap.size( ) )
                throw new GraphException( "Negative cycle detected" );

            for( Edge e : v.adj )
            {
                Vertex w = e.dest;
                double cvw = e.cost;
                
                if( w.dist > v.dist + cvw )
                {
                    w.dist = v.dist + cvw;
                    w.prev = v;
                      // Enqueue only if not already on the queue
                    if( w.scratch++ % 2 == 0 )
                        q.add( w );
                    else
                        w.scratch--;  // undo the enqueue increment    
                }
            }
        }
    }

    /**
     * Single-source negative-weighted acyclic-graph shortest-path algorithm.
     */
    public void acyclic( String startName )
    {
        Vertex start = vertexMap.get( startName );
        if( start == null )
            throw new NoSuchElementException( "Start vertex not found" );

        clearAll( ); 
        Queue<Vertex> q = new LinkedList<Vertex>( );
        start.dist = 0;
        
          // Compute the indegrees
  Collection<Vertex> vertexSet = vertexMap.values( );
        for( Vertex v : vertexSet )
            for( Edge e : v.adj )
                e.dest.scratch++;
            
          // Enqueue vertices of indegree zero
        for( Vertex v : vertexSet )
            if( v.scratch == 0 )
                q.add( v );
       
        int iterations;
        for( iterations = 0; !q.isEmpty( ); iterations++ )
        {
            Vertex v = q.remove( );

            for( Edge e : v.adj )
            {
                Vertex w = e.dest;
                double cvw = e.cost;
                
                if( --w.scratch == 0 )
                    q.add( w );
                
                if( v.dist == INFINITY )
                    continue;    
                
                if( w.dist > v.dist + cvw )
                {
                    w.dist = v.dist + cvw;
                    w.prev = v;
                }
            }
        }
        
        if( iterations != vertexMap.size( ) )
            throw new GraphException( "Graph has a cycle!" );
    }

    /**
     * Process a request; return false if end of file.
     */
    public static boolean processRequest( BufferedReader in, Graph g )
    {
        String startName = null;
        String destName = null;
        String alg = null;

        try
        {
            System.out.print( "Enter start node:" );
            if( ( startName = in.readLine( ) ) == null )
                return false;
            System.out.print( "Enter destination node:" );
            if( ( destName = in.readLine( ) ) == null )
                return false;
            System.out.print( " Enter algorithm (u, d, n, a ): " );   
            if( ( alg = in.readLine( ) ) == null )
                return false;
            
            if( alg.equals( "u" ) )
                g.unweighted( startName );
            else if( alg.equals( "d" ) )    
            {
                g.dijkstra( startName );
                g.printPath( destName );
                g.dijkstra2( startName );
            }
            else if( alg.equals( "n" ) )
                g.negative( startName );
            else if( alg.equals( "a" ) )
                g.acyclic( startName );
                    
            g.printPath( destName );
        }
        catch( IOException e )
          { System.err.println( e ); }
        catch( NoSuchElementException e )
          { System.err.println( e ); }          
        catch( GraphException e )
          { System.err.println( e ); }
        return true;
    }

    /**
     * A main routine that:
     * 1. Reads a file containing edges (supplied as a command-line parameter);
     * 2. Forms the graph;
     * 3. Repeatedly prompts for two vertices and
     *    runs the shortest path algorithm.
     * The data file is a sequence of lines of the format
     *    source destination.
     */
    public static void main( String [ ] args )
    {
        Graph g = new Graph( );
        try
        {
            FileReader fin = new FileReader( args[0] );
            BufferedReader graphFile = new BufferedReader( fin );

            // Read the edges and insert
            String line;
            while( ( line = graphFile.readLine( ) ) != null )
            {
                StringTokenizer st = new StringTokenizer( line );

                try
                {
                    if( st.countTokens( ) != 3 )
                    {
                        System.err.println( "Skipping ill-formatted line " + line );
                        continue;
                    }
                    String source  = st.nextToken( );
                    String dest    = st.nextToken( );
                    int    cost    = Integer.parseInt( st.nextToken( ) );
                    g.addEdge( source, dest, cost );
                }
                catch( NumberFormatException e )
                  { System.err.println( "Skipping ill-formatted line " + line ); }
             }
         }
         catch( IOException e )
           { System.err.println( e ); }

         System.out.println( "File read..." );
         System.out.println( g.vertexMap.size( ) + " vertices" );

         BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
         while( processRequest( in, g ) )
             ;
    }
}
No comments

Selasa, 14 Mei 2013

Perintah dasar di Linux [ Dari A- Z ]

Berikut ini adalah perintah-perintah Linux dari a sampai z.  Semoga bermanfaat :) terutama buat teman-teman yang sedang praktikum sistem operasi! sukses ! untuk saya juga haha.. Aamiin :D

a
addgroup Tambah grup ke sistem
alias Create an alias •
apropos Search Help halaman manual (man-k)
apt-get Mencari dan menginstal paket perangkat lunak (Debian)
aspell Spell Checker
awk Cari dan Ganti teks, database sort / validate / index


b
Strip basename direktori dan akhiran dari nama file
bash GNU Bourne-Again Shell
bc Arbitrary bahasa kalkulator presisi
bg Kirim ke latar belakang
break Keluar dari loop •
builtin menjalankan shell builtin
bzip2 Compress atau dekompresi file bernama (s)

c
cal Display a calendar
case Conditionally perform a command
cat Display the contents of a file
cd Change Directory
cfdisk Partition table manipulator for Linux
chgrp Change group ownership
chmod Change access permissions
chown Change file owner and group
chroot Run a command with a different root directory
chkconfig System services (runlevel)
cksum Print CRC checksum and byte counts
clear Clear terminal screen
cmp Compare two files
comm Compare two sorted files line by line
command Run a command - ignoring shell functions •
continue Resume the next iteration of a loop •
cp Copy one or more files to another location
cron Daemon to execute scheduled commands
crontab Schedule a command to run at a later time
csplit Split a file into context-determined pieces
cut Divide a file into several parts
d
date Display or change the date & time
dc Desk Calculator
dd Convert and copy a file, write disk headers, boot records
ddrescue Data recovery tool
declare Declare variables and give them attributes •
df Display free disk space
diff Display the differences between two files
diff3 Show differences among three files
dig DNS lookup
dir Briefly list directory contents
dircolors Colour setup for `ls'
dirname Convert a full pathname to just a path
dirs Display list of remembered directories
dmesg Print kernel & driver messages
du Estimate file space usage

e
echo Display message on screen •
egrep Search file(s) for lines that match an extended expression
eject Eject removable media
enable Enable and disable builtin shell commands •
env Environment variables
ethtool Ethernet card settings
eval Evaluate several commands/arguments
exec Execute a command
exit Exit the shell
expect Automate arbitrary applications accessed over a terminal
expand Convert tabs to spaces
export Set an environment variable
expr Evaluate expressions

f
false Do nothing, unsuccessfully
fdformat Low-level format a floppy disk
fdisk Partition table manipulator for Linux
fg Send job to foreground
fgrep Search file(s) for lines that match a fixed string
file Determine file type
find Search for files that meet a desired criteria
fmt Reformat paragraph text
fold Wrap text to fit a specified width.
for Expand words, and execute commands
format Format disks or tapes
free Display memory usage
fsck File system consistency check and repair
ftp File Transfer Protocol
function Define Function Macros
fuser Identify/kill the process that is accessing a file

g
gawk Find and Replace text within file(s)
getopts Parse positional parameters
grep Search file(s) for lines that match a given pattern
groups Print group names a user is in
gzip Compress or decompress named file(s)

h
hash Remember the full pathname of a name argument
head Output the first part of file(s)
help Display help for a built-in command •
history Command History
hostname Print or set system name

i
id Print user and group id's
if Conditionally perform a command
ifconfig Configure a network interface
ifdown Stop a network interface
ifup Start a network interface up
import Capture an X server screen and save the image to file
install Copy files and set attributes

j
join Join lines on a common field

k
kill Stop a process from running
killall Kill processes by name

l
less Display output one screen at a time
let Perform arithmetic on shell variables •
ln Make links between files
local Create variables •
locate Find files
logname Print current login name
logout Exit a login shell •
look Display lines beginning with a given string
lpc Line printer control program
lpr Off line print
lprint Print a file
lprintd Abort a print job
lprintq List the print queue
lprm Remove jobs from the print queue
ls List information about file(s)
lsof List open files

m
make Recompile a group of programs
man Help manual
mkdir Create new folder(s)
mkfifo Make FIFOs (named pipes)
mkisofs Create an hybrid ISO9660/JOLIET/HFS filesystem
mknod Make block or character special files
more Display output one screen at a time
mount Mount a file system
mtools Manipulate MS-DOS files
mv Move or rename files or directories
mmv Mass Move and rename (files)

n
netstat Networking information
nice Set the priority of a command or job
nl Number lines and write files
nohup Run a command immune to hangups
nslookup Query Internet name servers interactively

o
open Open a file in its default application
op Operator access

p
passwd Modify a user password
paste Merge lines of files
pathchk Check file name portability
ping Test a network connection
pkill Stop processes from running
popd Restore the previous value of the current directory
pr Prepare files for printing
printcap Printer capability database
printenv Print environment variables
printf Format and print data •
ps Process status
pushd Save and then change the current directory
pwd Print Working Directory

q
quota Display disk usage and limits
quotacheck Scan a file system for disk usage
quotactl Set disk quotas

r
ram ram disk device
rcp Copy files between two machines
read Read a line from standard input •
readarray Read from stdin into an array variable •
readonly Mark variables/functions as readonly
reboot Reboot the system
rename Rename files
renice Alter priority of running processes
remsync Synchronize remote files via email
return Exit a shell function
rev Reverse lines of a file
rm Remove files
rmdir Remove folder(s)
rsync Remote file copy (Synchronize file trees)

s
screen Multiplex terminal, run remote shells via ssh
scp Secure copy (remote file copy)
sdiff Merge two files interactively
sed Stream Editor
select Accept keyboard input
seq Print numeric sequences
set Manipulate shell variables and functions
sftp Secure File Transfer Program
shift Shift positional parameters
shopt Shell Options
shutdown Shutdown or restart linux
sleep Delay for a specified time
slocate Find files
sort Sort text files
source Run commands from a file `.'
split Split a file into fixed-size pieces
ssh Secure Shell client (remote login program)
strace Trace system calls and signals
su Substitute user identity
sudo Execute a command as another user
sum Print a checksum for a file
symlink Make a new name for a file
sync Synchronize data on disk with memory

t
tail Output the last part of files
tar Tape ARchiver
tee Redirect output to multiple files
test Evaluate a conditional expression
time Measure Program running time
times User and system times
touch Change file timestamps
top List processes running on the system
traceroute Trace Route to Host
trap Run a command when a signal is set(bourne)
tr Translate, squeeze, and/or delete characters
true Do nothing, successfully
tsort Topological sort
tty Print filename of terminal on stdin
type Describe a command •

u
ulimit Limit user resources •
umask Users file creation mask
umount Unmount a device
unalias Remove an alias •
uname Print system information
unexpand Convert spaces to tabs
uniq Uniquify files
units Convert units from one scale to another
unset Remove variable or function names
unshar Unpack shell archive scripts
until Execute commands (until error)
useradd Create new user account
usermod Modify user account
users List users currently logged in
uuencode Encode a binary file
uudecode Decode a file created by uuencode

v
v Verbosely list directory contents (`ls -l -b')
vdir Verbosely list directory contents (`ls -l -b')
vi Text Editor
vmstat Report virtual memory statistics

w
watch Execute/display a program periodically
wc Print byte, word, and line counts
whereis Search the user's $path, man pages and source files for a program
which Search the user's $path for a program file
while Execute commands
who Print all usernames currently logged in
whoami Print the current user id and name (`id -un')
Wget Retrieve web pages or files via HTTP, HTTPS or FTP
write Send a message to another user

x
xargs Execute utility, passing constructed argument list(s)
yes Print a string until interrupted
No comments

Sabtu, 11 Mei 2013

Antrian (Queue) dalam java


Antrian (Queue) merupakan representasi data yang hanya memperbolehkan pengaksesan data pada dua ujung. Penyisipan data dilakukan dibelakan (ekor) dan pengeluaran data dilakukan diujung (kepala). Berbeda dengan double lingked list pada praktikum 5 yang diperbolehkan mengakses data di sembarang tempat. Perilaku seperti ini meniru kejadian pada masalah antrian pada dunia nyata yakni yang pertama masuk dialah yang dilayani duluan (FIFO). :


Dua operasi pada antrian yakni enQueue dan deQueue.  Untuk  menyisipkan data pada antrian menggunakan enQueue dan menghapus data dari antrian menggunakan deQueue.

ADT Antrian
Dari ilustrasi gambar di atas ADT antrian dapat direpresentasikan sebagai berikut
                                          

Node                                              
Object data
Node next
Node(Object)
Node(Object,Node)
Object getObject()
Node getNext()
List
Node nodeAwal, nodeAkhir;
String nama;
public List()
public List( String namaList )     
public void sisipDiAwal(Object dt)     
public void sisipDiAkhir(Object dt)     
public Object hapusDrDepan()
public boolean kosong()                 
public void cetak()

 








Queue
List listAntrian
Queue()
enqueue(Object object)    
Object dequeue()    
boolean kosong()   
public void cetak()


Contoh Program Antrian :

Program Latihan Praktikum 8.1
pulic class Node {  
   Object data;
       Node next;

   Node( Object object ){this ( object, null );}

   Node( Object object, Node node ){
      data = object;
      next = node;
      }

   Object getObject(){return data;}

      Node getNext() {return next;}
}

Program Latihan Praktikum 8.2
public class List {
      private Node nodeAwal;
      private Node nodeAkhir;
      private String nama;
 
      public List(){    this( "list" ); }

   public List( String namaList ){
         nama = namaList;
         nodeAwal = nodeAkhir = null;
      }
     
   public void sisipDiAwal( Object dt ){
      if (kosong()) nodeAwal = nodeAkhir = new Node( dt );
      else nodeAwal = new Node( dt, nodeAwal );
      }
     
   public void sisipDiAkhir( Object dt ){
      if (kosong()) nodeAwal = nodeAkhir = new Node( dt );
      else nodeAkhir = nodeAkhir.next = new Node( dt );
   }
     
   public Object hapusDrDepan(){
      Object itemDihapus = null;
      if (!kosong()) {
              itemDihapus = nodeAwal.data;    
             if ( nodeAwal == nodeAkhir )
             nodeAwal = nodeAkhir = null;
             else nodeAwal = nodeAwal.next;    
      }

      return itemDihapus;
   }  

            public boolean kosong(){return nodeAwal == null;}
           
      public void cetak(){
        if ( kosong() ){
           System.out.printf( "Kosong %s\n", nama );
           return;
        }
     
        System.out.printf( "Isi %s adalah : ", nama );
        Node kini = nodeAwal;
     
        while ( kini != null ){
           System.out.printf( "%s ", kini.data );
           kini = kini.next;
        }
     
        System.out.println( "\n" );
      }
}

Program Latihan Praktikum 8.3
public class Queue {
    private List listAntrian;
    public Queue() {
       listAntrian = new List( "queue" );
    }
    
    public void enqueue( Object object ){
       listAntrian.sisipDiAkhir( object );
    }
    
    public Object dequeue(){
       return listAntrian.hapusDrDepan();
    }
    
    public boolean kosong(){
       return listAntrian.kosong();
    }
   
    public void cetak(){listAntrian.cetak();}
   
    public static void main( String args[]){
              Queue q = new Queue();           
              q.enqueue( 10 );
              q.cetak();       
              q.enqueue( 40 ); 
              q.cetak();      
              q.enqueue( 25 ); 
              q.cetak();      
              q.enqueue( 30 ); 
              q.cetak();
           
              Object dtHapus = null;
              while(!q.kosong()){
                     dtHapus = q.dequeue();
                     System.out.printf("%s dihapus \n",dtHapus );
                     q.cetak();
              }
     }   
 }

Screenshot Program :




Semoga bermanfaat. :)
5 comments