ADTs, Arrays, Linked Lists - York University · ADTs, Arrays, Linked Lists Outline and Required...

Preview:

Citation preview

1

ADTsADTs, Arrays, Linked Lists, Arrays, Linked Lists

Outline and Required Reading:Outline and Required Reading:

COSC 2011, Fall 2003, Section AInstructor: N. Vlajic

• ADTs (§ 2.1.2)• Arrays (§ 1.5)• Linked Lists (§ 4.3.1, 4.3.2)

2

Abstract Data Type – entity that consists of:1) data structure (DS)2) set of operation supported on the DS3) error conditions

Abstract Data Type (ADT)

“abstract” ⇒⇒⇒⇒ implementation details are not specified !

ADT

DataStructure

Interfaceadd()

remove()find()

request

result

Basic Data Structures •••• array(used in advanced ADT) •••• linked list

3

Abstract Data Type (ADT) (cont.)

DataStructure

Interfaceadd()

remove()find()

request

result

Designer’s responsibility:•••• choice of data structure•••• implementation of operations

User’s requirements:•••• correct performance•••• efficient performance

The interior mechanisms of an implemented ADTshould be hidden and inaccessible to the user!

(Remember encapsulation, i.e. information hiding, OO-programming principle!)

4

•••• standard ADTs are great reusable components - can be effectively used in solving many real

world problems

•••• we may be required to adapt algorithms whichuse some of the standard ADTs

Abstract Data Type (ADT) (cont.)

What should weknow aboutstandard ADTs?

Why should weknow standardADTs?

(1) what operations they support(2) complexity of supported operations(3) memory cost of operations

Standard ADTs Stacks, Queues, Vectors, Lists, Trees, …

5

0 1 2 3 4 5 6 7

ADT Taxonomy

Linear ADTs - we call an ADT “linear”, if the following is true:(1) there is a unique first element(2) there is a unique last element(3) every element has a unique predecessor (except 1st)(4) every element has a unique successor (except last)

A1 A2

Non-linear ADTs - if one or more of the above is not true, the ADT isnon-linear

A1

A2 A3 A1

6

Example 1 [ selecting an ADT ]

Abstract Data Type (ADT) (cont.)

(a) If organizing a tour route, where we have to add/delete a city - use Linked List.

(c) If managing a telephone directory that should provide shortsearch times - use Sorted Tree.

7

Array

Array – sequence of indexed components, with the followinggeneral properties:

• array size is fixed at the time of array’s constructionint numbers = new numbers [10];

• any array component can be efficiently inspected orupdated using its index, in O(1) timerandomNumber = numbers[5];numbers[2] = 100;

Major Limitation – size fixed, and must be known in advance

Index = 0 1 2 3 4 5 6 7

Array of length 8

Element atposition 5

8

Properties of Java Arrays

(1) for an array of length n, the index bounds are 0 and (n-1)

(2) array elements are stored in “side by side” memory locations

(3) every array is homogeneous - all its components must be ofthe same type

(4) an array is itself an object•••• it is allocated dynamically by means of “new”•••• it is automatically deallocated when no longer referred to

9

Linked List

Linked List – sequence of nodes arranged one after another, with eachnode connected to the next by a “link” (like a chain)

•••• each node is an object containing: 1) a single element - stored object or value2) links - reference to one or both neighbouring nodes

•••• each node (except the last one) has a successor, andeach node (except the first one) has a predecessor

A1 …head node tail node

∅∅∅∅A2 An

element link

node

∅∅∅∅

NOTE: neighbouring nodes can be “far away” physically!

10

Properties of Linked Lists

(1) linked list can be of any length, i.e. it can contain any numberof elements, and it can grow

(2) the element in any node can be accessed, however we musthold a link to that node

(3) nodes can be inserted and deleted ⇒⇒⇒⇒ ordering of nodes canbe changed in minimal running time

(4) there are two different types of linked lists

•••• Singly Linked ListSingly Linked List (each node is linked to one of its neighbours)•••• Doubly Linked ListDoubly Linked List (each node is linked to both of its neighbours)

11

Object Reference

Reference Variable – contains the location (address) of an object

•••• when we declare a reference variable, it does not reference anything, i.e. it is initialized to null

•••• if we attempt to use a reference variable beforeinitiating an object for it, NullPointerExceptionwill be thrown

Integer intRef;

intRef = new Integer(5);

nullReference intRef

5Reference intRef

Integer Object

12

Object Reference (cont.)

Integer p, q;p q

p = new Integer(5);p

5

p = new Integer(6); 5

6

p

q = p;p

q

6

DeclaringReference Variables

Allocatingan Object

Allocating Another Object

marked forgarbage collection

Assigninga Reference

13

Object Reference (cont.)

q = new Integer(9);

p = null;

q = p;p

q

6

Allocatingan Object

Assigning null toa Reference Variable

Assigning a Referencewith a null Value

p

q

6

9

p

q9

null

9

marked forgarbage collection

marked forgarbage collection

14

Singly Linked List

Singly – each node contains a data-element together with a link Linked List to its successor

A1 …head node tail node

∅∅∅∅A2 An∅∅∅∅

public class SLLNode {

Object element;SLLNode next;

public SLLNode(Object elem, SLLNode succ) {

this.element = elem;this.next = succ; }

}

Reference variables!

SLLNode

15

Singly Linked List (cont.)

SLLNode Complying with Requirements“hidden” and “inaccessible”

public class SLLNode {private Object element;private SLLNode next;public SLLNode(Object elem, SLLNode succ) {

this.element = elem;this.next = succ; }

public Object getElement() {return element; }

public SLLNode getNext() {return next; }

public void setElement(Object newElement){element = newElement; }

public void setNext(SLLNode newNext){next = newNext; }

}

16

Singly Linked List (cont.)

Creating and LinkingTwo SLLNodes

SLLNode n = new SLLNode(new Integer(5), null);n

5

n5

9first

SLLNode first = new SLLNode(NewInteger(9), n)

n5

9

SLLNode n = new SLLNode(NewInteger(9), n)

Should, in the 2nd case, the first node be collected by the garbage collection!?

17

Singly Linked List (cont.)

A1 … ∅∅∅∅A2 An-1∅∅∅∅

public class SLL {

private SLLNode head;private SLLNode tail;

public SLL() {this.head = null;this.tail = null;

…}

It is a good practice to maintain direct references to head and tail; with them:1) easy to delete or insert new node at the front of SLL;2) easy to insert new node at the rear.

But, it is still costly to delete the end node. Why?!

An

Constructs an emptylinked list!

SLL

head tail

18

Singly Linked List (cont.)

public class SLL {

private SLLNode head;. . .public void addLast(SLLNode newNode){

SLLNode curr;if (head==null) head=newNode;else {

for (curr = head; curr.getNext() != null; curr=curr.getNext()){ };curr.setNext=newNode; }

}}

Adding New Node at the Rear of SLL with Reference to Head Only!

A1 A2 An ∅∅∅∅∅∅∅∅currhead

19

Singly Linked List (cont)

Example 1 [ SLL traversal ]

public void traverseSLL() {

for (SLLNode curr = head; curr != null; curr = curr.getNext()) {

System.out.print(curr.element + “ “); } }

Example 2 [ deletion of 1st SLL node ]

public void deleteFirst() {. . . head = head.next; }

A1 A2∅∅∅∅

head

20

Singly Linked List (cont)

Example 3 [ deletion of 1st SLL node, with memory management ]

public void deleteFirst() {. . . curr = head;head = head.next; curr.setNext(null);curr = null;

}

A1 A2∅∅∅∅

head

…marked for

garbage collection

21

Singly Linked List (cont)

Example 4 [ deletion of SLL node after node referenced by “prev”]

public void delete(SLLNode prev) { . . .SLLNode curr = prev.getNext();prev.setNext(curr.getNext());curr.setNext(null);curr = null;

}

A1 Ak Ak+1∅∅∅∅prevhead

… …Ak+2

marked forgarbage collection

22

Singly Linked List (cont)

Example 5 [ insertion of SLL node after node referenced by “prev”]

public void insert(Object element) { . . .SLLNode curr = prev.getNext();SLLNode newNode = new SLLNode(element, curr);prev.setNext(newNode);

}

A1 Ak∅∅∅∅prevhead

… …Ak+1

Ak+1

23

Doubly Linked List

Doubly – each node contains an element together with a link to Linked List its predecessor and a link to its successor

public class DLLNode {

private Object element;private DLLNode prev, next;

public DLLNode(Object elem, SLLNode pred, DLLNode succ) {this.element = elem;this.prev = pred;this.next = succ; }

…}

A1 ∅∅∅∅A2 An∅∅∅∅

DLLNode

24

Arrays vs. Single- and Double- Linked Lists

Guidelines for Choosing Between an Array and a Linked List

ADT Requirement Suggested Implementation

frequent random access operations

add/remove at a cursor

frequent capacity changes

add/remove at a two-way cursor

Use an array.

Use a singly linked list.

Use a doubly linked list.

Use a linked list.

25

Questions

Q.1 Suppose, in your program, you have been using a collection ofnumbers, which has been stored in an array of size 1000, namedintCollection. (int intCollection = new int[1000];)However, you do not need this collection any longer, and you want to free the memory. What should you do?

Q.2 Examine the following code, and determine how the correspondingSLL (the sequence of SLL’s elements) looks like.

SLLNode c = new SLLNode( “not to be”, null);SLL phrase = SLL();phrase.head = new SLLNode(“to be”, new SLLNode(“or”, c) );

Q.3 Repeat Examples 1 to 5 for Doubly Linked List.

Q.4 Write a short program that swaps the 1st and 2nd node ofa) a singly linked list (SLL)b) a doubly linked list (DLL)

Recommended