# Algoritma & Struktur Data

## Presentasi berjudul: "Algoritma & Struktur Data"— Transcript presentasi:

Algoritma & Struktur Data
Linear List Teknik Informatika Universitas Muhammadiyah Malang SP

Representasi Linear List dengan Array dan Linked list

Tujuan Instruksional Mahasiswa mampu :
Memahami struktur data dari linear list Mampu merepresentasikan linear list menggunakan array dan linked list Mengimplementasikan linear list ke dalam program

Struktur Data Struktur data terdiri dari obyek data dan operasi-operasi. Obyek data adalah sekumpulan instance (model/sampling) Contoh obyek data : integer = {0, +1, -1, +2, -2, +3, -3, …} daysOfWeek = {S,M,T,W,Th,F,Sa} myDataObject = {apple, chair, 2, 5.2, red, green, Jack}

Struktur Data Struktur data dibedakan menjadi 2 jenis : Linear list
direpresentasikan dengan : array dan linked list Struktur data hirarki Direpresentasikan dengan : tree dan graph

Linear Lists Disebut juga dengan ordered list.
Bentuk instance dari linear list : (e0, e1, e2, …, en-1) where ei denotes a list element n >= 0 is finite (list size is n)

Linear Lists L = (e0, e1, e2, e3, …, en-1) relationships
e0 is the zero’th (or front) element en-1 is the last element ei immediately precedes ei+1 A data object is a set of instances; an instance of a linear list is an ordered set of elements.

Linear List Examples/Instances
Students in COP3530 = (Jack, Jill, Abe, Henry, Mary, …, Judy) Exams in COP3530 = (exam1, exam2, exam3) Days of Week = (S, M, T, W, Th, F, Sa) Months = (Jan, Feb, Mar, Apr, …, Nov, Dec) Size of Students in COP3530 is 240, Exams is 3, DOW is 7, and Months is 12. Notice that Days of Week is used as an example of both a data object and of a linear list. As a data object, {S, M, T, …} and {M, W, S, …} describe the same data object with 7 allowable instances S, M, T, … As a linear list (S, M, T, …) and (M, W, S, …) are two different instances of a linear list. Linear List itself may be viewed as data object, which is simply the set of all possible linear list instances.

Struktur data Operations
Operasi : aksi yang dapat dilakukan pada obyek data. Operasi-operasi yang umum pada obyek data : penambahan elemen, penghapusan elemen, pengaksesan elemen, dll.

Linear List Operations—size()
determine list size L = (a,b,c,d,e) size = 5

Linear List Operations—get(theIndex)
get element with given index L = (a,b,c,d,e) get(0) = a get(2) = c get(4) = e get(-1) = error get(9) = error

Linear List Operations—indexOf(theElement)
determine the index of an element L = (a,b,d,b,a) indexOf(d) = 2 indexOf(a) = 0 indexOf(z) = -1 The index of a nonexistent element is defined to be –1. When theElement is in the list an index between 0 and size()-1 is the result. So –1 would be an invalid index and is used to represent the case when theElement is not in the list

Linear List Operations—remove(theIndex)
remove and return element with given index L = (a,b,c,d,e,f,g) remove(2) returns c and L becomes (a,b,d,e,f,g) index of d,e,f, and g decrease by 1

Linear List Operations—remove(theIndex)
remove and return element with given index L = (a,b,c,d,e,f,g) remove(-1) => error remove(20) => error

add an element so that the new element has a specified index L = (a,b,c,d,e,f,g) add(0,h) => L = (h,a,b,c,d,e,f,g) index of a,b,c,d,e,f, and g increase by 1

L = (a,b,c,d,e,f,g) add(2,h) => L = (a,b,h,c,d,e,f,g) index of c,d,e,f, and g increase by 1 add(10,h) => error add(-6,h) => error

Data Structure Specification
Language independent Abstract Data Type Java Interface Abstract Class

Linear List Abstract Data Type
AbstractDataType LinearList { instances ordered finite collections of zero or more elements operations isEmpty(): return true if the list is empty, false otherwise size(): return the list size (i.e., number of elements in the list) get(index): return the indexth element of the list indexO f(x): return the index of the first occurrence of x in the list, return -1 if x is not in the list remove(index): remove and return the indexth element, elements with higher index have their index reduced by 1 add(theIndex, x): insert x as the indexth element, elements with theIndex >= index have their index increased by 1 output(): output the list elements from left to right }

Linear List as Java Interface
An interface may include constants and abstract methods (i.e., methods for which no implementation is provided).

Linear List as Java Interface
public interface LinearList { public boolean isEmpty(); public int size(); public Object get(int index); public int indexOf(Object elem); public Object remove(int index); public void add(int index, Object obj); public String toString(); } Should add comments that describe the parameters, return value, and functionality of each method. Looks a lot like the abstract data type specification but the data types, return type specification, name of output method (toString) are all peculiar to Java.

Implementing An Interface
public class ArrayLinearList implements LinearList { // code for all LinearList methods must be provided here }

Linear List As An Abstract Class
An abstract class may include constants, variables, abstract methods, and nonabstract methods. So an abstract class is more general than an interface. In addition to having the permissible components of an interface (constants and abstract methods), we can have variables and nonabstract methods.

Linear List As Java Abstract Class
public abstract class LinearListAsAbstractClass { public abstract boolean isEmpty(); public abstract int size(); public abstract Object get(int index); public abstract int indexOf(Object theElement); public abstract Object remove(int index); public abstract void add(int index, Object theElement); public abstract String toString(); } In the case of a linear list, the main difference between the interface and abstract class specification is the use of the keyword interface vs the keywords abstract class. All methods of the abstract class have been declared as abstract to indicate that we are not providing their implementation here. In the case of an interface it isn’t required (though permissible) to declare each method abstract. This is because all methods listed in an interface are, by default, abstract.

Extending A Java Class public class ArrayLinearList
extends LinearListAsAbstractClass { // code for all abstract classes must come here } Since ArrayLinearList is not declared as an abstract class, it must provide an implementation for all abstract methods of the class it extends (I.e., of LinearListAsAbstractClass).

Linear List Array Representation
use a one-dimensional array element[] 1 2 3 4 5 6 a b c d e All array representations of a linear list use an array (say one-dimensional). Element.length = 15. Different array representations result when different mappings are used between list elements and array positions. The most intuitive and simple mapping is to map list element I into array position I. L = (a, b, c, d, e) Store element i of list in element[i].

Representation Used In Text
1 2 3 4 5 6 a b c d e size = 5 put element i of list in element[i] use a variable size to record current number of elements This is the representation used in the text. When this mapping is used, list operations such as isEmpty(), size(), get(index) Become easy to implement.

Add/Remove An Element size = 5 add(1,g) size = 6 a b c d e a g b c d e
To add an element we must physically relocate elements that are to be to the right of the newly inserted element. We must also increment size by 1. The slide shows add(1,g). remove(1) is the reverse. To remove an element we must move elements to the right of the removed element left by 1 and reduce size by 1. a g b c d e size = 6

Data Type Of Array element[]
Data type of list elements is unknown. Define element[] to be of data type Object. Cannot put elements of primitive data types (int, float, double, char, etc.) into our linear lists. To use this representation in Java, we must know/provide a data type and length of the array element[]. Wrapper types Integer, Float, Double, etc provided in Java.

Increasing Array Length
Length of array element[] is 6. a b c d e f First create a new and larger array newArray = new Object[15];

Increasing Array Length
Now copy elements from old array to new one. a b c d e f a b c d e f

Increasing Array Length
Finally, rename new array. element = newArray; a b c d e f element[0] element.length = 15

Class ArrayLinearList
Merupakan hasil implements dari interface LinearList.

Create An Empty List ArrayLinearList a = new ArrayLinearList(100),
b = new ArrayLinearList(), c; LinearList d = new ArrayLinearList(1000), e = new ArrayLinearList(), f; For the second example, the class ArrayLinearList must implement the interface LinearList. c and f are actually set to null. So, they really are not referencing an empty linear list but the null list. If ArrayLinearList has methods that are not listed in LinearList then we’ll need to typecast d,e,f to ALL before performing any of these additional methods ((ArrayLinearList) d).newMethod().

Using A Linear List System.out.println(a.size());

Array Of Linear Lists LinearList [] x = new LinearList [4];
x[0] = new ArrayLinearList(20); x[1] = new Chain(); x[2] = new Chain(); x[3] = new ArrayLinearList(); for (int i = 0; i < 4; i++) x[i].add(0, new Integer(i)); Following first line, x[0:3] = null. The class Chain implements the interface LinearList. x[0].add(…) and x[3].add(…) invoke add method of ArrayLinearList while x[1].add and x[2].add result in the invocation of the add method of Chain.

The Class ArrayLinearList
/** array implementation of LinearList */ package dataStructures; import java.util.*; // has Iterator interface import utilities.*; // has array resizing class public class ArrayLinearList implements LinearList { // data members protected Object [] element; // array of elements protected int size; // number of elements in array // constructors and other methods come here } /** => documentation comment. Used by javadoc to create html documentation files. The documentation files index.html, packages.html, etc. that are part of the codes that you have downloaded were produced by running javadoc. However, the above comment doesn’t appear in the produced documentation, because the doc comment must immediately precede the class, method, or field it applies to. Package statement must come first; import statements must come next. Packages are like folders, used to organize/store your programs in folders for easy access and permit name reuse across folders/packages. Import java.lang.* is implicit. Import statements specify a path relative to (or one that extends) a path contained in classpath. Default: visible in package only. Protected: in package and subclasses (I.e., classes that extend this one). Private: only in class. Public: visible to all classes in all packages.

A Constructor /** create a list with initial capacity initialCapacity
IllegalArgumentException when * initialCapacity < 1 */ public ArrayLinearList(int initialCapacity) { if (initialCapacity < 1) throw new IllegalArgumentException ("initialCapacity must be >= 1"); // size has the default initial value of 0 element = new Object [initialCapacity]; } Note that code should verify input data and throw exceptions when this data is incorrect. Need have a throws statement in method header only if method throws an uncaught exception of type other than RuntimeException and Error.

Another Constructor public ArrayLinearList()
/** create a list with initial capacity 10 */ public ArrayLinearList() {// use default capacity of 10 this(10); } this(10) invokes the previous constructor.

The Method isEmpty true iff list is empty */ public boolean isEmpty() {return size == 0;}

The Method size() current number of elements in list */ public int size() {return size;}

/** @throws IndexOutOfBoundsException when
The Method checkIndex 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); } Note that checkIndex is not a public method. Visible only within the package. Could have made it protected instead. Then it would be visible only within the package dataStructures and classes that extend ALL.

The Method get /** @return element with specified index
IndexOutOfBoundsException when * index is not between 0 and size - 1 */ public Object get(int index) { checkIndex(index); return element[index]; }

The Method indexOf index of first occurrence of theElement, * return -1 if theElement not in list */ public int indexOf(Object theElement) { // search element[] for theElement for (int i = 0; i < size; i++) if (element[i].equals(theElement)) return i; // theElement not found return -1; } Note the use of the equals method. Default Object.equals method compares only references. This method must be overridden by user defined data types so that indexOf works correctly.

public Object remove(int index)
The Method remove public Object remove(int index) { checkIndex(index); // valid index, shift elements with higher index Object removedElement = element[index]; for (int i = index + 1; i < size; i++) element[i-1] = element[i]; element[--size] = null; // enable garbage collection return removedElement; }

if (index < 0 || index > size) // invalid list position throw new IndexOutOfBoundsException ("index = " + index + " size = " + size); // valid index, make sure we have space if (size == element.length) // no space, double capacity element = ChangeArrayLength.changeLength1D(element, 2 * size);

for (int i = size - 1; i >= index; i--)
The Method add // shift elements right one position for (int i = size - 1; i >= index; i--) element[i + 1] = element[i]; element[index] = theElement; size++; }

Faster Way To Shift Elements 1 Right
System.arraycopy(element, index, element, index + 1, size - index);

Convert To A String public String toString() {
StringBuffer s = new StringBuffer("["); // put elements into the buffer for (int i = 0; i < size; i++) if (element[i] == null) s.append("null, "); else s.append(element[i].toString() + ", "); if (size > 0) s.delete(s.length() - 2, s.length()); // remove last ", " s.append("]"); // create equivalent String return new String(s); } s.delete(start, end) … deletes characters from start to end-1.

Definisi Linked list : linear list yang dibangun dari satu atau lebih node. Node terdiri dari dua bagian : data field dan pointer. Data field: bagian dari list node untuk menyimpan data. Pointer : bagian dari list node untuk menunjuk node berikutnya.

Node Link atau pointer data field

Pointer bantu : firstnode

c a e d b firstNode pointer (or link) in e is null use a variable firstNode to get to the first element a

Normal Way To Draw A Linked List
b c d e null firstNode link or pointer field of node data field of node

Linked Lists vs Array A0 A1 A2 A3 Menyimpan koleksi elemen secara non-contiguously. Elemen dapat terletak pada lokasi memory yang saling berjauhan. Bandingkan dengan array dimana tiap-tiap elemen akan terletak pada lokasi memory yang berurutan. Mengizinkan operasi penambahan atau penghapusan elemen ditengah-tengah koleksi dengan hanya membutuhkan jumlah perpindahan elemen yang konstan. Bandingkan dengan array. Berapa banyak elemen yang harus dipindahkan bila akan menyisipi elemen ditengah-tengah array? con•tig•u•ous adj. 1 in physical contact; touching along all or most of one side 2 near, next, or adjacent SYN. adjacent

Chain firstNode null a b c d e A chain is a linked list in which each node represents one element. There is a link or pointer from one element to the next. The last node has a null pointer.

Node Representation package dataStructures; class ChainNode {
// package visible data members Object element; ChainNode next; // constructors come here } next element

Constructors Of ChainNode
null ChainNode() {} null element ChainNode(Object element) {this.element = element;} ChainNode(Object element, ChainNode next) {this.element = element; this.next = next;} next element

get(0) a b c d e null firstNode checkIndex(0); desiredNode = firstNode; // gets you to first node return desiredNode.element; Do a checkIndex first. Then move to desired node. Once you are at the desired node, you can return the element in that node as in return desiredNode.element; When firstNode = null, there is no element whose index is 0.

get(1) a b c d e null firstNode checkIndex(1); desiredNode = firstNode.next; // gets you to second node return desiredNode.element;

get(2) a b c d e null firstNode checkIndex(2); desiredNode = firstNode.next.next; // gets you to third node return desiredNode.element;

get(5) a b c d e firstNode checkIndex(5); // throws exception
null firstNode checkIndex(5); // throws exception desiredNode = firstNode.next.next.next.next.next; // desiredNode = null return desiredNode.element; // null.element Note that checkIndex would throw an exception. Other two statements executed only when checkIndex not done.

NullPointerException
a b c d e null firstNode desiredNode = firstNode.next.next.next.next.next.next; // gets the computer mad // you get a NullPointerException firstNode.next.next.next.next.next = null So desiredNode = null.next, which causes the null pointer exception.

Remove An Element remove(0) firstNode = firstNode.next; a b c d e
null firstNode remove(0) First do a checkIndex. Even though this change in value of firstNode leaves behind a pointer from the original first node to the new first node, the original first node is no longer part of the chain, because you cannot get to it from firstNode. The memory used by the original first node will be reclaimed automatically by Java’s garbage collector. firstNode = firstNode.next;

first get to node just before node to be removed
a b d e null firstNode c b beforeNode c first get to node just before node to be removed beforeNode = firstNode.next;

now change pointer in beforeNode
remove(2) firstNode null a b c d e beforeNode now change pointer in beforeNode beforeNode.next = beforeNode.next.next;

b c d e null firstNode f newNode Step 1: get a node, set its data and link fields First, do a checkIndex. ChainNode newNode = new ChainNode(new Character(‘f’), firstNode);

add(0,’f’) firstNode newNode Step 2: update firstNode
b c d e null firstNode f newNode Step 2: update firstNode firstNode = newNode;

firstNode = new ChainNode( new Character(‘f’), firstNode);
One-Step add(0,’f’) a b c d e null firstNode f newNode firstNode = new ChainNode( new Character(‘f’), firstNode);

first find node whose index is 2
add(3,’f’) a b c d e null firstNode f newNode beforeNode c first find node whose index is 2 next create a node and set its data and link fields ChainNode newNode = new ChainNode(new Character(‘f’), beforeNode.next); finally link beforeNode to newNode beforeNode.next = newNode;

c d e null firstNode f newNode beforeNode beforeNode = firstNode.next.next; beforeNode.next = new ChainNode(new Character(‘f’), beforeNode.next);

Definisi Linked list dengan dua pointer(next & prev)
Pointer next : menghadap ke node yang lebih besar indexnya. Pointer prev : menghadap ke node yang lebih kecil indexnya.

Gambaran last Data/item prev next

Double Representation
class Node { Object dData; // data item Node next; // pointer next Node prev; // pointer prev ….. }

Operasi Penambahan/penyisipan Penghapusan

Penambahan Node

Penambahan Node Penambahan di awal Penambahan di akhir
Penambahan sebelum node tertentu Penambahan setelah node tertentu

Asumsi awal

Penambahan di Awal Pointer bantu : baru Langkah : Baru.next = head

Penambahan di Awal(1) last

Penambahan di Awal(2) last

Penambahan di Awal(3) last

Penambahan di Akhir Asumsi linked list awal : last

Penambahan di Akhir 1. Baru.prev = last last

Penambahan di Akhir 2. last.next = Baru last

Penambahan di Akhir 3. last = Baru last

Penambahan Setelah Node x
Pointer bantu : after

Penambahan Setelah Node x
Asumsi linked list awal : last

Penambahan Setelah Node x
Node after; after diarahkan ke posisi node 10, bisa dimulai dari head maupun last last

Penambahan Setelah Node x
2. Baru.prev = after last

Penambahan Setelah Node x
3. Baru.next = after.next last

Penambahan Setelah Node x
4. after.next.prev = Baru last

Penambahan Setelah Node x
5. after.next = Baru last

Penambahan Setelah Node x
Hasil akhir : last

Penambahan Sebelum Node x
Asumsi linked list awal : last

Penambahan Sebelum Node x
Node before; before diarahkan ke posisi node 5, bisa dimulai dari head maupun last last

Penambahan Sebelum Node x
2. Baru.prev = before.prev last

Penambahan Sebelum Node x
3. Baru.next = before last

Penambahan Sebelum Node x
4. before.prev.next = Baru last

Penambahan Sebelum Node x
5. before.prev = Baru last

Penambahan Sebelum Node x
Hasil akhir : last

Penghapusan Node

Operasi Hapus Node (Delete)
Hapus awal (Delete First) Hapus akhir (Delete Last) Hapus Node x

Asumsi Awal Asumsi linked list awal : last

Delete First 1. Node hapus; hapus = head; last

Delete First 2. head.next.prev = null last

Delete First 3. head = hapus.next last

Delete First last

Delete First Hasil akhir : last

Delete Last Asumsi linked list awal : last

Delete Last 1. Node hapus; hapus = last; last

Delete Last 2. last.prev.next = null last

Delete Last 3. last = hapus.prev last

Delete Last last

Delete Last Hasil akhir : last

Delete Node x Asumsi linked list awal :  Misalkan x = 3 last last

Delete Node x Node hapus;
hapus diarahkan pada posisi node 3, bisa mulai dari head maupun last last

Delete Node x 2. hapus.prev.next = hapus.next; last

Delete Node x 3. hapus.next.prev = hapus.prev; last

Delete Node x last

Circular List

Definisi Circular List : list yang berbentuk cirrcular/melingkar, node depan terhubung dengan node paling belakang.

a b c d current Menyisipkan X pada lokasi setelah current. a x b c d x current

Langkah-langkah menyisipkan yang lebih efisien
tmp = new ListNode (x, current.next); current.next = tmp; a b x current a b x current

Latihan Buatlah sebuah method untuk menghitung jumlah elemen dalam sebuah linked list! public static int listSize (LinkedList theList)‏ { }

Variasi Linked Lists Doubly-linked lists: Tiap list node menyimpan referensi node sebelum dan sesudahnya. Berguna bila perlu melakukan pembacaan linkedlist dari dua arah. A head tail prev next

Variasi Linked Lists Circular-linked lists: Node terakhir menyimpan referensi node pertama. Dapat diterapkan dengan atau tanpa header node. A B C first prev next

newNode = new DoublyLinkedListNode(x); 1 newNode.prev = current; 2 newNode.prev.next = newNode; a 2 b ? 1 x current

A B 4 3 X prev next 2 5 current 1 6 newNode 1 newNode = new DoublyLinkedListNode(x); 2 newNode.prev = current; 3 newNode.next = current.next; 4 newNode.prev.next = newNode; 5 newNode.next.prev = newNode; 6 current = newNode;

current.prev.next = current.next; current.next.prev = current.prev; current = current.prev; 1 a b 2 3 current x

Rangkuman ListNode List, LinkedList dan variasinya Iterator class
Kelebihan & kekurangan dari linked list Growable Overhead a pointer, new operator untuk membuat node. Hanya bisa diakses secara sequential.

Gambaran a b c d e firstNode

Daftar Pustaka L.N. Harnaningrum, Struktur Data menggunakan Java, Graha ilmu, 2010 Siswanto, Algoritma & Struktur Data Linier, Graha Ilmu, 2010 Ruli Manurung, Ade Azurat, Struktur Data dan Algoritma, Fasilkom UI, 2008

Presentasi serupa