Contoh Program Linked List dalam Bahasa Java


class Link
{
public int iData; // data item (key)
public double dData; // data item
public Link next; // next link in list
public Link(int id, double dd) // constructor
{
iData = id; // initialize data
dData = dd; // (‘next’ is automatically
} // set to null)

public void displayLink() // display ourself
{
System.out.print(“{” + iData + “, ” + dData + “} “);
}
} // end class Link
class LinkList
{
private Link first; // ref to first link on list
public LinkList() // constructor
{
first = null; // no items on list yet
}
public boolean isEmpty() // true if list is empty
{
return (first==null);
}
public void insertFirst(int id, double dd)
{ // make new link
Link newLink = new Link(id, dd);
newLink.next = first; // newLink –> old first
first = newLink; // first –> newLink
}
public Link deleteFirst() // delete first item
{ // (assumes list not empty)
Link temp = first; // save reference to link
first = first.next; // delete it: first–>old next
return temp; // return deleted link
}
public void displayList()
{
System.out.print(“List (first–>last): “);
Link current = first; // start at beginning of list
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 LinkListApp
{
public static void main(String[] args)
{
LinkList theList = new LinkList(); // make new list
theList.insertFirst(22, 2.99); // insert four items
theList.insertFirst(44, 4.99);
theList.insertFirst(66, 6.99);
theList.insertFirst(88, 8.99);
theList.displayList(); // display list
while( !theList.isEmpty() ) // until it’s empty,
{
Link aLink = theList.deleteFirst(); // delete link
System.out.print(“Deleted “); // display it
aLink.displayLink();
System.out.println(“”);
}
theList.displayList(); // display list
} // end main()
} // end class LinkListApp

// sumber: Data Structures and Algorithm, Sam Publishing

3 Responses to Contoh Program Linked List dalam Bahasa Java

  1. sirodjudinsirodjudin says:

    outputnya kok kosong ya

    • bluejundi says:

      kok di pc saya muncul output apt ini ya, mas:
      List (first–>last): {88, 8.99} {66, 6.99} {44, 4.99} {22, 2.99}
      Deleted {88, 8.99}
      Deleted {66, 6.99}
      Deleted {44, 4.99}
      Deleted {22, 2.99}
      List (first–>last):

  2. sirodjudinsirodjudin says:

    saya salah apanya ya, udah muter2 gak ketemu juga.
    boleh minta kirim file javanya?
    buat perbandingan.
    terimakasih.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: