Download LECT#23

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Array data structure wikipedia , lookup

Quadtree wikipedia , lookup

Red–black tree wikipedia , lookup

Lattice model (finance) wikipedia , lookup

Interval tree wikipedia , lookup

Binary tree wikipedia , lookup

Binary search tree wikipedia , lookup

Linked list wikipedia , lookup

B-tree wikipedia , lookup

Transcript
Abstract Data Types –II
Overview
 List Abstract Data type.
 Static (Array) Implementation of List ADT.
 Problems with Array Implementation.
 Dynamic Implementation of List ADT.
 Preview: Abstract Data Types III.
Lecture 25
1
List Abstract Data Type
 A general list of size n takes the form A0, A2, A3,..., An-1.
A list of size 0 is an empty list.
 For any list except the empty list Ai+1 follows Ai (i<n) and
Ai-1 precedes Ai (i>0). The first element of the list is A0 and
the last element is An-1 . The position of element Ai in the list is
i.
 Associated with this definition we should provide a set of
suitable list operations which can be used to manipulate the list,
for example insert, delete and retrieveKth which, respectively,
insert, delete and returns the element in some position from the
given list etc.
Lecture 25
2
List Abstract Data Type – Cont’d
 A List ADT might provide the following operations:







isEmpty()
insert(p, e)
delete(p)
retrieve(p)
update(p,e)
clear()
length()
- tests if the list is empty
- inserts element e at position p in the list
- removes element at position p in the list
- returns element at position p from the list
- updates element at position p with e
- removes all elements from list
- returns the length of list
 Some examples of using these list operations (list starts at 0):
list = ( 7, 4, 1 )
insert(0, 5) = ( 5, 7, 4, 1 )
insert(length(), 3) = ( 5, 7, 4, 1, 3 )
retrieve(0) = 5
update(3,6) = ( 5, 7, 4, 6, 3 )
delete(length()) = ERROR
delete(length()-1) = ( 5, 7, 4, 6 )
isEmpty() = False
Lecture 25
3
Array Implementation of List
 A simple solution would be to base the list on an array:
 simple to implement
 but estimate of size of list is required upfront
 elements can be retrieved from the list in constant time
 list traversal can occur in linear time
 insertion and deletion are expensive.
 e.g. inserting a new element at position 0 (the beginning)
requires shifting all elements down one space in the array to
make room, whereas deleting the first element requires shifting
all elements in the array up one.
 In the worst case insertion and deletion is an order(N) operation
and on average order(N/2) so linear time is still required.
 Building a list by successive inserts at position 0 in list would
require quadratic time.
Lecture 25
4
Inserting/Deleting an Element
0
13
1
30
2
45
3
4
n-1
15
Move elements from position 1 up one place
Insert 5 here
13
5
30
0
1
2
13
5
30
45
3
45
15
4
n-1
15
Move elements from position 3 down one place
Delete this
5
30
45
15
Lecture 25
5
Problems with Array Implementation
 So when implementing data structures using arrays, we
need to be careful with the size of array chosen:
 too big: wasteful of space.
 too small: unsuitable for the application.
 performance: can be an issue for certain operations because of
need to move array elements around.
 An alternative is to use a dynamic list structure which is
able to grow and shrink as the application demands:
 no estimate of size is required upfront.
 Does not suffer from performance problems outlined earlier with
an array implementation.
 These structures are also known as linked lists
Lecture 25
6
Dynamic Linked List Structures
element next
element next
element
next
header
List Nodes
 Each node consists of a data element and reference which points to
the next node in the list.
 The last node reference is initialised to a null value and this is used to
terminate the list.
Implementation Issues
 If a header reference is used to point to the 1st list node:
 insertion and deleting first element requires the header to be updated to
reflect the changes to the start of the list.
 deleting in general requires that we keep track of the node in front of
the one to be deleted so that the links can be updated.
Lecture 25
7
Solution - Using a Dummy Header Node
next
element next
element next
element
next
dummy header
List Nodes
 Using a dummy header node solves the problems outlined
earlier with a header reference.
 To solve deletion problems we need to provide a
findPrevious method which returns a reference to the
predecessor of the node we wish to delete.
 If we delete the first node then findPrevious will return the
header node whose next reference can be updated.
 Inserting a new first node only requires that the header
next reference be updated to point to the new first node.
Lecture 25
8
LinkedList Node Implementation
 If an abstract data type is to be truly abstract then the type of the
element that it is used to manage should be irrelevant.
 We will therefore store instances of the base Java Object type in our
node which is represented by a Java class as follows.
public class Node {
private Object element;
private Node next;
// Object type stored in this node
// reference to another node
// class methods go here
}
 The structure is self-referential in nature as the reference which is
part of the class is also capable of referring to a ListNode (i.e. itself).
 A node class should also provide an appropriate set of constructors
and node interface methods.
Lecture 25
9
LinkedList Node Implementation
public class Node {
private Object element;
private Node next;
// object type stored in this node
// reference to the next node in the list
// default constructor
public Node() {
element = null;
next = null;
}
// constructor initialises node with new element + reference to next node
public Node(Object e, Node n) {
element = e;
next = n;
}
// continued on next slide
Lecture 25
10
Node Manipulation Methods
public void setElement(Object newElem) {
element = newElem;
}
// set new element
public void setNext(Node newNext) {
next = newNext;
}
// set new next node
public Object getElement() {
return element;
}
// return element in this node
public Node getNext() {
return next;
}
// return reference to next node
}
Lecture 25
11
Creating and Manipulating a New List Node
 Create a new Node object using new operator which allocates
memory from heap, and an appropriate Node constructor.
first
Node first = new Node(“a”,null);
a
element next
second
Node second = new Node(“b”,first);
second.setElement(“c”);
b
a
second
first
c
Lecture 25
first
a
12
Linked List Implementation
 A LinkedList is represented by a class as follows:
public class LinkedList {
private Node header;
private int length;
public LinkedList() {
header = new Node();
length = 0;
}
// list sentinel header node
// record length of list
// default constructor initialises list
// create sentinel header node
// set length to 0
// other class methods go here
}
 Implementation details of the LinkedList class methods are
shown in next slide. We assume list elements are indexed
from 0.
Lecture 25
13
General Purpose Linked List Methods
 Empty a List by ensuring header next reference is null.
List (Header)
public void clear() {
// initialise a list
header.setNext(null);
}
 A LinkedList is empty if the header next reference is null.
 To obtain a reference to the first node return header next reference.
e
List (Header)
public Node getHead() {
// return first node
return header.getNext();
}
public boolean isEmpty() {
// test if list is empty
return (header.getNext() == null);
}
public boolean length() {
// return list length
return length;
}
Lecture 25
14
Insert Node at Index Position (starting at 0)
 Add the new node at index position 1
e
header
Old links
New links
previous
d
newNode
a
public void insert(int index, Object e) throw IndexOutOfBoundsException {
if ((index < 0 || index > length))
throw new IndexOutOfBoundsException(“index invalid”);
Node previous = this.nodeAt(index-1); // locate previous node
Node newNode = new Node(e,previous.getNext()); // create new node
previous.setnext(newNode);
// previous node points to new node
length++;
// increment length
}
 Assume existence of nodeAt(int) - a LinkedList method which returns a
reference to a node at the specified index.
Lecture 25
15
Remove Node at Index Position
 Remove the node located at index position 0
a
Header (p)
deleted node
d
Old links
New links
e
reclaimed by garbage collector
public void remove(int index) throws IndexOutOfBoundsException {
if ((index < 0 || index >= length))
throw new IndexOutOfBoundsException(”invalid index”);
Node p = this.nodeAt(index-1);
// locate previous node
p.setNext(p.getNext().getNext()); // disconnect deleted node
length--;
// decrement length
}
Lecture 25
16
Update Node at Index Position
 Update the data element of node located at index position 1
e
header
f
d
Update element ‘a’
in this node to ‘f’
public void update(int index, Object e) throws indexOutOfBoundsException {
if ((index < 0 || index >= length))
throw new IndexOutOfBoundsException(”invalid index”);
this.nodeAt(index).setElement(e);
}
Lecture 25
17
Find Location of Element in List
 Update the data element of node located at index position 1
e
header
f
d
indexOf(“f”) == 1
indexOf(“p”) == -1
public int indexOf(Object e) { //
int index = 0;
for (Node n = header.getNext(); n != null; n = n.getNext()) {
if (e.equals(n.getElement()))
return index;
index++;
}
return -1;
}
Lecture 25
18