Anda di halaman 1dari 20

PRAKTIKUM ALGORITMA DAN STRUKTUR DATA

MODUL KE-2
LIST LINEAR
SINGLE & DOUBLE LINKED LIST

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

LATIHAN
Petunjuk :
Cobalah untuk menjalankan semua contoh program dibawah ini. Program pada latihan 1
dan latihan 2 masing-masing memiliki method yang melakukan operasi linked list
dengan menggunakan index. Tambahkan beberapa method pada latihan 1 dan 2
tersebut, seperti method addFirst, addLast, dsb. Perbaikilah program tersebut jika
terdapat kesalahan saat compile program. Analisa hasil dan kode program untuk
mengerjakan tugas praktikum.
1. Contoh program : class node untuk single linked list
class ChainNode
{
// package visible data members
Object element;
ChainNode next;
// package visible constructors
ChainNode() {}
ChainNode(Object element)
{this.element = element;}
ChainNode(Object element, ChainNode next)
{this.element = element;
this.next = next;}
}
2. Contoh program : class node untuk double linked list
class DoubleNode
{
// package visible data members
Object element;
DoubleNode next;
DoubleNode previous;
// package visible constructors
DoubleNode() {}
DoubleNode(Object theElement)
{element = theElement;}
DoubleNode(Object theElement, DoubleNode thePrevious, DoubleNode theNext)
{
element = theElement;
previous = thePrevious;
next = theNext;
}
}
3. Contoh program : single linked list
import java.util.*;

public class Chain


{
// data members
protected ChainNode firstNode;
protected int size;
// constructors
/** create a list that is empty */
public Chain(int initialCapacity)
{
// the default initial values of firstNode and size
// are null and 0, respectively
}
public Chain()
{this(0);}
// methods
/** @return true iff list is empty */
public boolean isEmpty()
{return size == 0;}
/** @return current number of elements in list */
public int size()
{return size;}
/** @throws IndexOutOfBoundsException when
* index is not between 0 and size - 1 */
void checkIndex(int index)
{
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException
("index = " + index + " size = " + size);
}
/** @return element with specified index
* @throws IndexOutOfBoundsException when
* index is not between 0 and size - 1 */
public Object get(int index)
{
checkIndex(index);
// move to desired node
ChainNode currentNode = firstNode;
for (int i = 0; i < index; i++)
currentNode = currentNode.next;
return currentNode.element;
}
/** @return index of first occurrence of theElement,

* return -1 if theElement not in list */


public int indexOf(Object theElement)
{
// search the chain for theElement
ChainNode currentNode = firstNode;
int index = 0; // index of currentNode
while (currentNode != null &&
!currentNode.element.equals(theElement))
{
// move to next node
currentNode = currentNode.next;
index++;
}
// make sure we found matching element
if (currentNode == null)
return -1;
else
return index;
}
/** Remove the element with specified index.
* All elements with higher index have their
* index reduced by 1.
* @throws IndexOutOfBoundsException when
* index is not between 0 and size - 1
* @return removed element */
public Object remove(int index)
{
checkIndex(index);
Object removedElement;
if (index == 0) // remove first node
{
removedElement = firstNode.element;
firstNode = firstNode.next;
}
else
{ // use q to get to predecessor of desired node
ChainNode q = firstNode;
for (int i = 0; i < index - 1; i++)
q = q.next;
removedElement = q.next.element;
q.next = q.next.next; // remove desired node
}
size--;
return removedElement;
}
/** Insert an element with specified index.
* All elements with equal or higher index

* have their index increased by 1.


* @throws IndexOutOfBoundsException when
* index is not between 0 and size */
public void add(int index, Object theElement)
{
if (index < 0 || index > size)
// invalid list position
throw new IndexOutOfBoundsException
("index = " + index + " size = " + size);
if (index == 0)
// insert at front
firstNode = new ChainNode(theElement, firstNode);
else
{ // find predecessor of new element
ChainNode p = firstNode;
for (int i = 0; i < index - 1; i++)
p = p.next;
// insert after p
p.next = new ChainNode(theElement, p.next);
}
size++;
}
/** convert to a string */
public String toString()
{
StringBuffer s = new StringBuffer("[");
// put elements into the buffer
ChainNode currentNode = firstNode;
while(currentNode != null)
{
if (currentNode.element == null)
s.append("null, ");
else
s.append(currentNode.element.toString() + ", ");
currentNode = currentNode.next;
}
if (size > 0)
s.delete(s.length() - 2, s.length()); // remove last ", "
s.append("]");
// create equivalent String
return new String(s);
}
/** create and return an iterator */
public Iterator iterator()
{return new ChainIterator();}

/** chain iterator */


private class ChainIterator implements Iterator
{
// data member
private ChainNode nextNode;
// constructor
public ChainIterator()
{nextNode = firstNode;}
// methods
/** @return true iff list has a next element */
public boolean hasNext()
{return nextNode != null;}
/** @return next element in list
* @throws NoSuchElementException
* when there is no next element */
public Object next()
{
if (nextNode != null)
{
Object elementToReturn = nextNode.element;
nextNode = nextNode.next;
return elementToReturn;
}
else
throw new NoSuchElementException("No next element");
}
/** unsupported method */
public void remove()
{
throw new UnsupportedOperationException
("remove not supported");
}
}
/** test program */
public static void main(String [] args)
{
// test default constructor
Chain x = new Chain();
// test size
System.out.println("Initial size is " + x.size());
// test isEmpty
if (x.isEmpty())
System.out.println("The list is empty");
else System.out.println("The list is not empty");

// test put
x.add(0, new Integer(2));
x.add(1, new Integer(6));
x.add(0, new Integer(1));
x.add(2, new Integer(4));
System.out.println("List size is " + x.size());
// test toString
System.out.println("The list is " + x);
// test indexOf
int index = x.indexOf(new Integer(4));
if (index < 0)
System.out.println("4 not found");
else System.out.println("The index of 4 is " + index);
index = x.indexOf(new Integer(3));
if (index < 0)
System.out.println("3 not found");
else System.out.println("The index of 3 is " + index);
// test get
System.out.println("Element at 0 is " + x.get(0));
System.out.println("Element at 3 is " + x.get(3));
// test remove
System.out.println(x.remove(1) + " removed");
System.out.println("The list is " + x);
System.out.println(x.remove(2) + " removed");
System.out.println("The list is " + x);
if (x.isEmpty())
System.out.println("The list is empty");
else System.out.println("The list is not empty");
System.out.println("List size is " + x.size());
// output using an iterator
Iterator y = x.iterator();
System.out.print("The list is ");
while (y.hasNext())
System.out.print(y.next() + " ");
System.out.println();
}
}
4. Contoh Program : double linked list
import java.util.*;
public class DoublyLinkedList
{
// data members

protected DoubleNode firstNode;


protected DoubleNode lastNode;
protected int size;
// constructors
/** create a list that is empty */
public DoublyLinkedList(int initialCapacity)
{
// the default initial values of firstNode and lastNode
// are null; the default for size is 0
}
public DoublyLinkedList()
{this(0);}
// methods
/** @return true iff list is empty */
public boolean isEmpty()
{return size == 0;}
/** @return current number of elements in list */
public int size()
{return size;}
/** @throws IndexOutOfBoundsException when
* index is not between 0 and size - 1 */
void checkIndex(int index)
{
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException
("index = " + index + " size = " + size);
}
/** @return element with specified index
* @throws IndexOutOfBoundsException when
* index is not between 0 and size - 1 */
public Object get(int index)
{
checkIndex(index);
DoubleNode currentNode;
// move to desired node
if (index < size / 2)
{// move from left to right
currentNode = firstNode;
for (int i = 0; i < index; i++)
currentNode = currentNode.next;
}
else
{// move from right to left
currentNode = lastNode;

int numberToMove = size - index - 1;


for (int i = 0; i < numberToMove; i++)
currentNode = currentNode.previous;
}
return currentNode.element;
}
/** @return index of first occurrence of elem,
* return -1 if elem not in list */
public int indexOf(Object elem)
{
// search the list for elem
DoubleNode currentNode = firstNode;
int index = 0; // index of currentNode
while (currentNode != null &&
!currentNode.element.equals(elem))
{
// move to next node
currentNode = currentNode.next;
index++;
}
// make sure we found matching element
if (currentNode == null)
return -1;
else
return index;
}
/** Remove the element with specified index.
* All elements with higher index have their
* index reduced by 1.
* @throws IndexOutOfBoundsException when
* index is not between 0 and size - 1
* @return removed element */
public Object remove(int index)
{
checkIndex(index);
DoubleNode currentNode; // will point to node with element that is
// to be removed
// move to element that is to be removed
if (index < size / 2)
{// move from left to right
currentNode = firstNode;
for (int i = 0; i < index; i++)
currentNode = currentNode.next;
}
else
{// move from right to left

currentNode = lastNode;
int numberToMove = size - index - 1;
for (int i = 0; i < numberToMove; i++)
currentNode = currentNode.previous;
}
// currentNode has the element that is to be removed
if (size == 1) // list becomes empty
firstNode = null;
else
// nonempty list remains
if (index == 0)
{// remove first node
firstNode = firstNode.next;
firstNode.previous = null;
}
else
if (index == size - 1)
{// remove last node
lastNode = lastNode.previous;
lastNode.next = null;
}
else
{// remove from interior
currentNode.previous.next = currentNode.next;
currentNode.next.previous = currentNode.previous;
}
size--;
return currentNode.element;
}
/** Insert an element with specified index.
* All elements with equal or higher index
* have their index increased by 1.
* @throws IndexOutOfBoundsException when
* index is not between 0 and size */
public void add(int index, Object theElement)
{
if (index < 0 || index > size)
// invalid list position
throw new IndexOutOfBoundsException
("index = " + index + " size = " + size);
if (index == 0)
{// insert at front
firstNode = new DoubleNode(theElement, null, firstNode);
if (firstNode.next == null)
// list was empty before this insert
lastNode = firstNode;
else
firstNode.next.previous = firstNode;
}
else

if (index == size)
{// insert at end of nonempty list
lastNode.next = new DoubleNode(theElement, lastNode, null);
lastNode = lastNode.next;
}
else
{// insert in interior
// find index - 1'th node
DoubleNode currentNode;
if (index <= size / 2)
{// move from left to right
currentNode = firstNode;
for (int i = 0; i < index - 1; i++)
currentNode = currentNode.next;
}
else
{// move from right to left
currentNode = lastNode;
int numberToMove = size - index;
for (int i = 0; i < numberToMove; i++)
currentNode = currentNode.previous;
}
// insert after currentNode
currentNode.next =
new DoubleNode(theElement, currentNode, currentNode.next);
currentNode.next.next.previous = currentNode.next;
}
size++;
}
/** convert to a string */
public String toString()
{
StringBuffer s = new StringBuffer("[");
if (size != 0)
{// nonempty list
// do first element
s.append(firstNode.element.toString());
DoubleNode currentNode = firstNode.next;
while (currentNode != null)
{
s.append(", " + currentNode.element.toString());
currentNode = currentNode.next;
}
}
s.append("]");
// create equivalent String
return new String(s);
}

/** create and return an iterator */


public Iterator iterator()
{return new DoubleIterator();}
/** iterator */
private class DoubleIterator implements Iterator
{
// data member
private DoubleNode nextNode;
// constructor
public DoubleIterator()
{nextNode = firstNode;}
// methods
/** @return true iff list has a next element */
public boolean hasNext()
{return nextNode != null;}
/** @return next element in list
* @throws NoSuchElementException
* when there is no next element */
public Object next()
{
if (nextNode != null)
{
Object elementToReturn = nextNode.element;
nextNode = nextNode.next;
return elementToReturn;
}
else throw new NoSuchElementException("No next element");
}
/** unsupported method */
public void remove()
{
throw new UnsupportedOperationException
("remove not supported");
}
}
/** Make the list empty. */
public void clear()
{
firstNode = null;
size = 0;
}
/** Add theElement to the right end of the list. */
public void add(Object theElement)
{

DoubleNode newNode = new DoubleNode(theElement, lastNode, null);


if (size == 0)
{// list is empty
firstNode = lastNode = newNode;
firstNode.previous = null;
}
else
{// attach newNode next to lastNode
lastNode.next = newNode;
newNode.previous = lastNode;
lastNode = newNode;
}
size++;
}
/** test program */
public static void main(String [] args)
{
// test default constructor
DoublyLinkedList x = new DoublyLinkedList();
// test size
System.out.println("Initial size is " +
x.size());
// test isEmpty
if (x.isEmpty())
System.out.println("The list is empty");
else System.out.println("The list is not empty");
// test add
x.add(0, new Integer(3));
x.add(1, new Integer(6));
x.add(0, new Integer(2));
x.add(2, new Integer(4));
x.add(4, new Integer(8));
x.add(4, new Integer(7));
x.add(3, new Integer(5));
x.add(0, new Integer(0));
x.add(1, new Integer(1));
System.out.println("List size is " + x.size());
// test toString
System.out.println("The list is " + x);
// test indexOf
int index = x.indexOf(new Integer(4));
if (index < 0)
System.out.println("4 not found");
else
System.out.println("The index of 4 is " + index);

index = x.indexOf(new Integer(3));


if (index < 0)
System.out.println("3 not found");
else
System.out.println("The index of 3 is " + index);
// test get
System.out.println("Element at 0 is " + x.get(0));
System.out.println("Element at 3 is " + x.get(3));
System.out.println("Element at 5 is " + x.get(5));
System.out.println("Element at 6 is " + x.get(6));
System.out.println("Element at 8 is " + x.get(8));
// test remove
System.out.println("Removed " + x.remove(0) + " the list is " + x);
System.out.println("Removed " + x.remove(7) + " the list is " + x);
System.out.println("Removed " + x.remove(2) + " the list is " + x);
System.out.println("Removed " + x.remove(3) + " the list is " + x);
if (x.isEmpty())
System.out.println("The list is empty");
else
System.out.println("The list is not empty");
System.out.println("List size is " + x.size());
// output using an iterator
Iterator ix = x.iterator();
System.out.print("The list is ");
while (ix.hasNext())
System.out.print(ix.next() + " ");
System.out.println();
// append an element
x.add(new Integer(99));
System.out.println("After appending 99, the list is " + x);
// make empty, then append
x.clear();
x.add(new Integer(6));
System.out.println("After appending 6 to an empty list, the list is " + x);
System.out.println("List size is " + x.size());
}
}

5. Contoh Program : method penambahan dari depan


Single list
void addFirst(Node input){
if (isEmpty()){
head=input;
tail=input;

}
else
{
input.pointer = head;
head = input;
} size++;
}

Double linked list


void addFirst(Node2P input){
if (isEmpty()){
head=input;
tail=input;
}
else
{
input.next = head;
head.previous = input;
head = input;
} size++;
}

6. Contoh program : method penambahan method dari belakang


Single list
void addLast(Node input){
if (isEmpty()){
head = input;
tail = input;
}
else
{
tail.pointer = input;
tail = input;
} size++;
}

Double linked list


void addLast(Node2P input){
if (isEmpty()){
head = input;
tail = input;
}
else
{
input.previous = tail;
tail.next = input;
tail = input;
} size++;
}

7. Contoh program : method penambahan setelah node tertentu


Single list
void insertAfter(Object key,Node input){
Node temp = head;
do{
if(temp.data==key){
input.pointer = temp.pointer;
temp.pointer = input;
size++;
System.out.println("Insert data is succeed.");
break;
}
temp = temp.pointer;
}while (temp!=null);
}

Double linked list


void insertAfter(Object key,Node2P input){
Node2P temp = head;
do{
if(temp.data==key){
input.previous = temp;
input.next = temp.next;
temp.next.previous = input;
temp.next = input;
size++;
System.out.println("Insert data is succeed.");
break;
}
temp = temp.next;
}while (temp!=null);
}

8. Contoh program : method penambahan sebelum node tertentu


Single list
void insertBefore(Object key,Node input){
Node temp = head;
while (temp != null){
if ((temp.data == key)&&(temp == head))
{
this.addFirst(input);
System.out.println("Insert data is succeed.");
break;
}
else if (temp.pointer.data == key)
{ input.pointer = temp.pointer;
temp.pointer = input;

System.out.println("Insert data is succeed.");


break;
}
temp = temp.pointer;
}
}

Double linked list


void insertBefore(Object key,Node2P input){
Node2P temp = head;
while (temp != null){
if (temp.data == key)
{
if(temp == head)
{
this.addFirst(input);
System.out.println("Insert data is succeed.");
size++;
break;
}
else
{
input.previous = temp.previous;
input.next = temp;
temp.previous.next = input;
temp.previous = input;
System.out.println("Insert data is succeed.");
size++;
break;
}
}
temp = temp.next;
}

9. Contoh program : method penghapusan node depan


Single list
void removeFirst(){
Node temp = head;
if (!isEmpty()){
if (head == tail)
head = tail = null;
else
{
temp = temp.pointer;
head = temp;
temp = null;
} size--;
}

else
System.out.println("Data is empty!");
}

Double linked list


void removeFirst(){
Node2P temp = head;
if (!isEmpty()){
if (head == tail)
head = tail = null;
else
{
head.next.previous = null;
head = temp.next;
} size--;
}
else
System.out.println("Data is empty!");
}

10. Contoh progrm : method penghapusan node belakang


Single list
void removeLast(){
Node temp = head;
if (!isEmpty()){
if (tail == head){
head = tail = null;
}
else {
while (temp.pointer != tail){
temp = temp.pointer;
}
temp.pointer = null;
tail = temp;
temp = null;
} size--;
}
else System.out.println("Data is empty!");
}

Double linked list


void removeLast(){
Node2P temp = tail;
if (!isEmpty()){
if (tail == head){

head = tail = null;


}
else {
tail.previous.next = null;
tail=temp.previous;
} size--;
}
else System.out.println("Data is empty!");
}

11. Contoh program : method penghapusan node tertentu


Single list
void remove(Object key){
Node temp = head;
if (!isEmpty()){
while (temp != null){
if (temp.pointer.data == key){
temp.pointer = temp.pointer.pointer;
if(temp.pointer == null)
tail=temp;
break;
}
else if ((temp.data == key)&&(temp == head)){
this.removeFirst();
break;
}
temp = temp.pointer;
}
}
else
System.out.println("Data is empty!");
size--;
}

Double linked list


void remove(Object key){
Node2P temp = head;
if (!isEmpty()){
while (temp != null){
if (temp.data == key){
if (temp == head){
this.removeFirst();
size--;
break;
}
else
{
temp.previous.next = temp.next;

temp.next.previous = temp.previous;
if(temp.next == null)
tail=temp;
size--;
break;
}
}
temp = temp.next;
}
}
else
System.out.println("Data is empty!");
size--;
}

12. Contoh program : penggunaan class linked list yang disediakan oleh java
import java.util.LinkedList;
public class KelasLinkedList {
public static void main(String[] args)
{
LinkedList linkedlist = new LinkedList();
linkedlist.add("satu");
linkedlist.add(1,"dua");
System.out.println("Keluaran 1");
for(int i=0;i<linkedlist.size();i++)
{
System.out.println(linkedlist.get(i));
}
linkedlist.add(1,"tiga");
System.out.println("keluaran 2");
for(int i=0;i<linkedlist.size();i++)
{
System.out.println(linkedlist.get(i));
}
linkedlist.add("empat");
System.out.println("keluaran 3");
for(int i=0;i<linkedlist.size();i++)
{
System.out.println(linkedlist.get(i));
}
linkedlist.add("lima");
System.out.println("keluaran 4");
for(int i=0;i<linkedlist.size();i++)
{
System.out.println(linkedlist.get(i));
}
}
}