22
CS/CE 2336 Computer Science II Session 11 OO Data Structures – Lists, Stacks, Queues UT D Adapted from D. Liang’s “Introduction to Java Programming, 8 th Ed.” 2

UT D CS/CE 2336 Computer Science IIjsk061000/Session_11.pdf · CS/CE 2336 Computer Science II ... after the index to the left by one position and decrease the list ... • A linked

  • Upload
    vuque

  • View
    223

  • Download
    0

Embed Size (px)

Citation preview

CS/CE 2336

Computer Science II

Session 11

OO Data Structures – Lists, Stacks, Queues

UT D

Adapted from D. Liang’s “Introduction to Java Programming, 8th Ed.”

2

What is a Data Structure?

• A collection of data structured (organized) in some fashion

• A data structure not only stores data, but also supports the operations for manipulating data in the structure in a certain way– E.g., an array is a data structure that holds a collection

of data in sequential order

– Array manipulation: store, retrieve, and modify data in entries of the array, find the size of the array etc…

• Array is simple and easy to use but it has limitations

3

4

Limitations of Arrays

• Once created, the size of an array cannot be altered

(cannot grow or shrink)!

• Array provides inadequate support for many

operations on its elements

– Inserting and deleting

– Sorting and searching

• Arrays are in a sense a static data structure

• But many applications require dynamic data

structures

– Data structures that can change dynamically at run-time

Object-Oriented Data Structures

• In object-oriented paradigm, a data structure is an object that stores other objects, referred to as data or elements

– Some time data structure is referred to as a container object or a collection object

– To define a data structure is essentially to declare a class

• The class for a data structure should use data fields to store elements and provide methods to support operations on its elements

– To create a data structure is therefore to create an instance from the class

– Methods of the instance are used to manipulate the data structure: inserting, deleting etc…

5

Four Classic Data Structures

• Four classic dynamic data structures to be introduced in this chapter: list, stack, queue and binary tree

• A list is a collection of data stored sequentially that supports insertion and deletion anywhere in the list

• A stack can be perceived as a special type of the list where insertions and deletions take place only at the one end, referred to as the top of a stack

• A queue represents a special list where insertions take place at the back (also referred to as the tail of) of a queue and deletions take place from the front (also referred to as the head of) of a queue

• A binary tree is a data structure to support efficient searching, sorting, inserting, and deleting data

6

7

Lists

• A list is a popular data structure to store data in sequential order

• For example, a list of students, a list of available rooms, a list of cities, and a list of books, etc. can be stored using lists

• Common operations on a list

– Retrieve an element from the list

– Insert a new element to the list

– Delete an element from the list

– Find how many elements are in the list

– Determine if an element is in the list

– Determine if the list is empty (contains zero element)

Implementing a List

• Two ways to implement a list can be considered: array and linked structure

• Array– Array is used to store the elements

– The array is dynamically created

– If the capacity of the array is exceeded, create a new larger array and copy all the elements from the current array to the new array

• Linked structure– A linked structure consists of nodes

– Each node is dynamically created to hold an element

– All the nodes are linked together to form a list

8

9

Design of ArrayList and LinkedList• For convenience, let’s name these two classes: MyArrayList

and MyLinkedList– These two classes have common operations, but different data fields

– The common operations can be generalized in an interface or an abstract class

• A good strategy is to combine the virtues of interfaces and abstract classes by providing both interface and abstract class in the design

– The user can use either the interface or the abstract class whichever is convenient

– Such an abstract class is known as a convenience class

M yL ist MyA bstractL ist

MyA rrayL is t

MyLi nked Lis t

MyList Interface and MyAbstractList Class

10

MyList

MyAbstractList

«interface» MyList<E>

+add(e: E) : void

+add(index: int, e: E) : void

+clear(): void

+contains(e: E): boolean

+get(index: int) : E

+indexOf(e: E) : int

+isEmpty(): boolean

+lastIndexOf(e: E) : int

+remove(e: E): boolean

+size(): int

+remove(index: int) : E

+set(index: int, e: E) : E

Appends a new element at the end of this list.

Adds a new element at the specified index in this list.

Removes all the elements from this list.

Returns true if this list contains the element.

Returns the element from this list at the specified index.

Returns the index of the first matching element in this list.

Returns true if this list contains no elements.

Returns the index of the last matching element in this list.

Removes the element from this list.

Returns the number of elements in this list.

Removes the element at the specified index and returns the removed element.

Sets the element at the specified index and returns the element you are replacing.

MyAbstractList<E>

#size: int

#MyAbstractList()

#MyAbstractList(objects: E[])

+add(e: E) : void

+isEmpty(): boolean

+size(): int

+remove(e: E): boolean

The size of the list.

Creates a default list.

Creates a list from an array of objects.

Implements the add method.

Implements the isEmpty method.

Implements the size method.

Implements the remove method.

Array Lists

• Array is a fixed-size data structure: once an array is created, its size cannot be changed but it can be used to implement dynamic data structures

• The trick is to create a new larger array to replace the current array if the current array cannot hold new elements in the list:

– Initially an array is created with a default size

– When inserting a new element into the array, first ensure there is enough room in the array

– If not create a new array with the size as twice as the current one

– Copy the elements from the current array to the new array

– The new array now becomes the current array

11

Array List Animation

www.cs.armstrong.edu/liang/animation/ArrayListAnimation.html

12

Insertion

Before inserting a new element at a specified index, shift all the elements after the index to the right and increase the list size by 1

13

e0

0 1 … i i+1 k-1 Before inserting e at insertion point i

e1 … ei ei+1

… ek-1

data.length -1 Insertion point e

e0

0 1 … i i+1 After inserting e at insertion point i, list size is incremented by 1

e1 … e ei

… ek-1

data.length -1 e inserted here

ek

ek

k

ei-1

ei-1

k+1 k

ei+1

i+2

…shift…

Deletion

To remove an element at a specified index, shift all the elements after the index to the left by one position and decrease the list size by 1

14

e0

0 1 … i i+1 k-1 Before deleting the element at index i

e1 … ei ei+1

… ek-1

data.length -1 Delete this element

e0

0 1 … i After deleting the element, list size is decremented by 1

e1 …

… ek

data.length -1

ek

k

ei-1

ei-1

k-1

ei+1

k-2

ek-1

…shift…

Implementing MyArrayList

15

MyArrayList TestList

MyArrayList<E>

-data: E[]

+MyArrayList()

+MyArrayList(objects: E[])

-ensureCapacity(): void

MyAbstractList<E>

Creates a default array list.

Creates an array list from an array of objects.

Doubles the current array size if needed.

Linked Lists

• MyArrayList is implemented using an array– The methods get(int index)and set(intindex, Object o) for accessing and modifying an element through an index and the add (Object o) for adding an element at the end of the list are efficient

– But the methods add(int index, Object o) and remove(int index)are inefficient – Why?

– Because it requires shifting potentially a large number of elements

– A new technique is required!

• How about linked structures– A linked structure improves efficiency for adding and

removing an element anywhere in a list

16

Linked List Animation

www.cs.armstrong.edu/liang/animation/LinkedListAnimation.html

17

Nodes in Linked Lists

• A linked list consists of nodes, each node contains an element, and each node is linked to its next neighbor

• A node can be defined as a class, as follows:

18

class Node<E> {

E element;

Node next;

public Node(E o) {

element = o;

}

}

element

head

ne xt

Node 1

element

next

Node 2 …

element

null

Node n

tail

Adding Three Nodes

• The variable head refers to the first node in the list, and the variable tail refers to the last node in the list

• If the list is empty, both are null• For example, you can create three nodes to store

three strings in a list, as follows:

19

Step 1: Declare head and tail:

The lis t is empty now Node<String> head = null;

Node<String> tail = null;

Adding Three Nodes - cont’d

20

Step 2: Create the first node and insert it to the list:

head "Chicago" next: null

tail

After the fi rst node is inserted inserted

head = new Node<String>("Chicago"); tail = head;

Adding Three Nodes - cont’d

21

Step 3: Create the second node and insert it to the list:

tail.next = new Node<String>("Denver");

head "Chicago" next

"Denver" next: null

tail

tail = tail.next;

head "Chicago" next

"Denver" next: null

tail

Adding Three Nodes - cont’d

22

Step 4: Create the third node and insert it to the list:

head "Chicago" next

"Dallas" next: null

tail

"Denver" next

tail.next = new Node<String>("Dallas");

head "Chicago" next

"Dallas" next: null

tail

"Denver" next

tail = tail.next;

Traversing All Elements in the List

• Each node contains the element and a data field named

next that points to the next element (the link)

• If the node is the last in the list, its data field next contains

the value null

– This property can be used to detect the last node

• List traversal

23

Node<E> current = head;

while (current != null) {

System.out.println(current.element);

current = current.next;

}

MyLinkedList

24MyLinkedList

MyLinkedList<E>

-head: Node<E>

-tail: Node<E>

+MyLinkedList()

+MyLinkedList(objects: E[])

+addFirst(e: E): void

+addLast(e: E): void

+getFirst(): E

+getLast(): E

+removeFirst(): E

+removeLast(): E

1

m Node<E>

element: E next: Node<E>

Link

1

MyAbstractList<E>

Creates a default linked list.

Creates a linked list from an array of objects.

Adds the object to the head of the list.

Adds the object to the tail of the list.

Returns the first object in the list.

Returns the last object in the list.

Removes the first object from the list.

Removes the last object from the list.

Implementing addFirst(E o)

public void addFirst(E o) {Node<E> newNode = new Node<E>(o);newNode.next = head;head = newNode;size++;if (tail == null)

tail = head;}

25

head

e0

next

A new node to be inserted here

ei

next

ei+1

next

tail

… ek

null

element

next

New node inserted here

(a) Before a new node is inserted.

(b) After a new node is inserted.

e0

next

… ei

next

ei+1

next

tail

… ek

null

element

next

head

Implementing addLast(E o)public void addLast(E o) {

if (tail == null) {head = tail = new Node<E>(element);

}else {tail.next = new Node(element);tail = tail.next;

}size++;

}

26

head

e0

next

… ei

next

ei+1

next

tail

… ek

null

o

null

New node inserted here

(a) Before a new node is inserted.

(b) After a new node is inserted.

head

e0

next

… ei

next

ei+1

next

tail

… ek

next

A new node to be inserted here

o

null

Implementing add(int index, E o)

public void add(int index, E o) {if (index == 0) addFirst(o);else if (index >= size) addLast(o);else {Node<E> current = head;for (int i = 1; i < index; i++)current = current.next;

Node<E> temp = current.next;current.next = new Node<E>(o);(current.next).next = temp;size++;

}} 27

current head

e0

next

A new node to be inserted here

ei

next

temp

ei+1

next

tail

… ek

null

e

null (a) Before a new node is inserted.

current head

e0

next

A new node is inserted in the list

ei

next

temp

ei+1

next

tail

… ek

null

e

next (b) After a new node is inserted.

Implementing removeFirst()

public E removeFirst() {if (size == 0) return null;else {

Node<E> temp = head;head = head.next;size--;if (head == null) tail = null;return temp.element;

}} 28

head

e0

next

Delete this node

ei

next

ei+1

next

tail

… ek

null

(a) Before the node is deleted.

(b) After the first node is deleted

e1

next

… ei

next

ei+1

next

tail

… ek

null

e1

next

head

29

Implementing removeLast()public E removeLast() {if (size == 0) return

null;else if (size == 1){

Node<E> temp = head;head = tail = null;size = 0;return temp.element;

}else{

Node<E> current = head;for (int i = 0; i <

size - 2; i++)current =

current.next;Node temp = tail;tail = current;tail.next = null;size--;return temp.element;

}}

head

e0

next

Delete this node

ek-2

next

ek-1

next

tail

ek

null

(a) Before the node is deleted.

(b) After the last node is deleted

e1

next

current

head

e0

next

… ek-2

next

ek-1

null

e1

next

tail

Implementing remove(int index)

public E remove(int index){if (index < 0 || index >=

size) return null;else if (index == 0) return

removeFirst();else if (index == size - 1)

return removeLast();else {Node<E> previous = head;for (int i = 1; i < index;

i++) {previous =

previous.next;}Node<E> current =

previous.next;previous.next =

current.next;size--;return current.element;

}}

30

previous head

element

next

Node to be deleted

element

next

element

next

tail

… element

null

element

next

(a) Before the node is deleted.

current

previous head

element

next

… element

next

element

next

tail

… element

null

(b) After the node is deleted.

current.next

current.next

Circular Linked Lists

• A circular, singly linked list is like a singly linked

list, except that the pointer of the last node

points back to the first node

31

element

head

next

Node 1

element

next

Node 2 …

element

next

Node n

tail

Doubly Linked Lists

• A doubly linked list contains the nodes with two pointers (links)

• One points to the next node and the other points to the

previous node

• These two pointers are conveniently called a forward pointer

and a backward pointer – Why two pointers?

– A doubly linked list can be traversed both ways: forward and backward

32

element

head

next

Node 1

element

next

Node 2 …

element

null

Node n

tail

null previous previous

Circular Doubly Linked Lists

• A circular, doubly linked list is doubly linked list,

except that the forward pointer of the last node

points to the first node and the backward pointer of

the first pointer points to the last node

33

element

head

next

Node 1

element

next

Node 2 …

element

next

Node n

tail

previous previous previous

Stacks

• A stack can be viewed as a special type of list, where the elements are accessed, inserted, and deleted only from the end, called the top, of the stack

34

Data1 Data2

Data1 Data1 Data2 Data3

Data1 Data2 Data3

Data1 Data2

Data3

Data1

Data2 Data1

Queues• A queue can be viewed as a special type of list, where

the elements are inserted into the end (tail) of the queue, and are accessed and deleted from the beginning (head) of the queue

35

Data1 Data2

Data1 Data1 Data2 Data3

Data1 Data2 Data3

Data2 Data3

Data1

Data3

Data2 Data3

Stack Animation

www.cs.armstrong.edu/liang/animation/StackAnimation.html

36

Queue Animation

www.cs.armstrong.edu/liang/animation/QueueAnimation.html

37

Implementing Stacks and Queues

• How do we implement a Stack?

• How do we implement Queue?

• Since the insertion and deletion operations on a stack are made only at the end of the stack, using an array list to implement a stack is more efficient than a linked list

• Since deletions and insertions are made at the beginning and the end of the list, it is more efficient to implement a queue using a linked list than an array list

38

Design of the Stack and Queue Classes

Two ways to design the stack and queue classes:

– Using inheritance: declare the stack class by extending the array list class, and the queue class by extending the linked list class

39

MyArrayList MyStack MyLinkedList MyQueue

– Using composition: You can declare an array list as a data field in the stack class, and a linked list as a data field in the queue class

MyStack

MyArrayList MyQueue MyLinkedList

Composition is Better

• Both designs are fine, but using composition is better

• Why?

– Because composition enables the definition of a complete new stack class and queue class with only necessary attributes and methods

– No need to inherit the unnecessary and inappropriate methods from the array list and linked list

40

MyStack and MyQueue

41

MyStack -list: MyArrayList

+isEmpty(): boolean

+getSize(): int

+peek(): Object

+pop(): Object

+push(o: Object): Object

+search(o: Object): int

Returns true if this stack is empty.

Returns the number of elements in this stack.

Returns the top element in this stack.

Returns and removes the top element in this stack.

Adds a new element to the top of this stack.

Returns the position of the specified element in this stack.

MyStack

MyQueue<E>

-list: MyLinkedList<E>

+enqueue(e: E): void

+dequeue(): E

+getSize(): int

Adds an element to this queue.

Removes an element from this queue.

Returns the number of elements from this queue.

MyQueue

Examples Using Stacks and Queues

Write a program that creates a stack using MyStackand a queue using MyQueue. It then uses the push(enqueue) method to add strings to the stack (or

queue) and the pop (dequeue) method to remove

strings from the stack (or queue).

42

TestStackQueue

Priority Queue• A regular queue is a first-in and first-out data structure

– Elements are appended to the end of the queue and are removed from the beginning of the queue

• In a priority queue, elements are assigned with priorities– When accessing elements, the element with the highest priority is

removed first• A priority queue has a largest-in, first-out behavior

– E.g., in the emergency room in a hospital assigns patients with priority numbers; the patient with the highest priority is treated first

43MyPriorityQueue TestPriorityQueue

MyPriorityQueue<E>

-heap: Heap<E>

+enqueue(element: E): void

+dequeue(): E

+getSize(): int

Adds an element to this queue.

Removes an element from this queue.

Returns the number of elements from this queue.