480 likes | 495 Views
MFE5008 Algorithmic Design and Analysis. Review of Array, Linked List, pp. 171-240 Stacks: pp. 279-319 Queues: pp. 325-362. 1. Array. Lists are very pervasive in computing, e.g., class list, list of charts, list of events One very simple implementation is to use Java arrays. int[] scores;
E N D
MFE5008 Algorithmic Design and Analysis Review of Array, Linked List, pp. 171-240 Stacks: pp. 279-319 Queues: pp. 325-362
1. Array • Lists are very pervasive in computing, e.g., class list, list of charts, list of events • One very simple implementation is to use Java arrays int[] scores; scores = new int[4]; scores[2] = 90; scores 90 [0] [1] [2] [3] MFE5008
Inserting into an Array • Insert has to shift upwards to create gap size score 5 a0 a1 a2 a3 a4 1. shift 6 a0 a1 it a2 a3 a4 write into gap update size Example: insert (3, it); MFE5008
Coding of Inserting into an Array class ObjectList { private int size; private Object[m] arr; public void insert(int j, Object it) { // pre: 0 <= j <= size for (i=size-1; i>=j; i=i-1) { arr[i+1] = arr[i]; } // step 1: create gap arr[j]=it; // step 2: write to gap size = size + 1; // step 3: update size } MFE5008
Notice: Object used in the Previous Example • For generality of the code • We can change Object to any of the Java primitive types. For example, by changing it to int we obtain an IntList • We continue to use it for other examples MFE5008
Deleting from an Array • Delete has to shift downwards to close gap of the deleted item size score 5 a0 a1 it a3 a4 1. close gap 4 a1 it a3 a4 2. update size Example: delete (0); MFE5008
Java Coding of Deleting from an Array class ObjectList { private int size; private Object[m] arr; public void delete(int j) { // pre: 0 <= j <= size-1 for (i=j+1; i<=size; i=i+1) { arr[i-1] = arr[i]; } // step 1: close gap size = size - 1; // step 2: update size } MFE5008
Summary of Array Approach • Retrieval is straightforward and fast • Deletion and insertion are slow since it has to shift items in its contiguous memory MFE5008
10 15 13 7 null 2. Linked-List • Definition: A linked list is a sequence of elements arranged one after another, with each element connected to the next element by a “link”. node = element + link (next) MFE5008
An Example • Contact of secrete agents: Nancy, Hugh, Judy, Tom, Ronald MFE5008
For this presentation, each node in the linked list is a class, as shown here. Declaring a Class for Nodes public class ListNode { private Object element; private ListNode next; ListNode(Object o) { element = o; next = null}; ListNode(Object o, ListNode n) { element = o; next = n }; } element next a0 MFE5008
Notice: ListNode used in the Previous Example • Each ListNode also contains a link which refers to another ListNode. MFE5008
10 15 13 7 null Head Nodes, Tail Nodes • head/tail: a reference to the first/last node in a linked list ListNode head; ListNode tail; tail head MFE5008
Motivation to use Head/Tail • Whenever a program builds and manipulates a linked list, the nodes are accessed through one or more references to nodes. Typically, a program includes a reference to the first node (the head) and a reference to the last node (the tail) MFE5008
Example: a sequence of items • A program can keep track of the front node by using a variable such as head in this example. • Notice that head is NOT a ListNode -- it is a reference to a ListNode. represent null head a0 a1 a2 a3 MFE5008
Example of a Linked-List ADT • This can help hide unnecessary internal details. IntNode() getLink() getData() listCopy() listPart() removeNodeAfter() listPosition() listCopyWithTail() setData() listSearch() listLength() setLink() MFE5008
Constructor • public IntNode(int initialData, IntNode initialLink); • Initialize a node with a specified initial data and link • Precondition: • initialData and initialLink must be in the correct types • Parameters: • initialData & initialLink • Postcondition: • this new node contains the “initialData” and links to the “initialLink” (page 175-176) MFE5008
addNodeAfter • public void addNodeBefore(int element); • Modification method to add a new node before the current node in the list. The new node will become the current node. • Precondition: none • Parameter: • element-the data to be placed in the new node • Postcondition: • a new node has been created with the data set to element. The new node will be inserted in the list before the current node (page 182-183) MFE5008
Example IntNode intList= new IntNode(1, null); intList.addNodeAfter(2); intList.addNodeAfter(3); link intList 2 1 link intList 3 2 1 MFE5008
Implementation, page 208 class IntNode { private int data; private IntNode link; public IntNode(int initialData, IntNode initialLink) { data=initialData; link=initialLink; } publivoid addNodeBefore(int element) // notice that “link” is updated after the method // so the new node is inserted at the beginning of the list { link=new IntNode(element, link); } }; MFE5008
Insertion: two steps indicated by 1 and 2 temp o current link 1 2 4 3 2 1 current link temp 2 o 4 3 2 1 1 MFE5008
Deletion current link 1 a0 a1 a2 a3 current link 1 a0 a1 a2 a3 MFE5008
Example: pp. 204-210 • Class IntNode • http://www.cs.colorado.edu/~main/docs/edu.colorado.nodes.IntNode.html • Constructor & Methods • function • parameters • precondition • postcondition • throws MFE5008
Implementation • Java implementation of IntNode • http://www.cs.colorado.edu/~main/edu/colorado/nodes/IntNode.java MFE5008
Summary • A linked-list is a sequence of elements arranged one after another, with each element connected to the next element by a link • It is easy and fast to remove and insert a node using linked-list MFE5008
3. Stacks • Stacks can be implemented efficiently and are very useful in computing • Stacks exhibit the LIFO (Last In First Out) behavior push(o) pop MFE5008
Stack ADT Interface interface Stack { // returns a new empty stack Stack makeStack( ); // returns true if empty boolean isEmpty( ); // insert o into stack void push(Object o); // remove most recent item void pop( ) throws underflow; // retrieve most recent item Object top( ) throws underflow; // return and remove most recent item Object topAndPop( ) throws underflow; } MFE5008
Example s s Stack s = new makeStack( ); s.push((Object) a); s.push((Object) b); s.push((Object) c); d=s.top( ); s.push(Object) e); s.pop( ) d e c c b b a a MFE5008
Applications of Stacks • line editing • bracket matching • postfix calculation • function call stack MFE5008
Line Editing • A line editor would place characters read into buffer but may use a backspace symbol (denoted by ) to do error correction Input: !dlrow olleHan :tuptuO Corrected Input: !dlrow olleHan :tuptuO Reversed Output: Output: Hello world! MFE5008
Informal Procedure Initialise a new stack; For each character read: . if it is a backspace, pop out last char entered; . if not a backspace, push the char into stack; To print in reverse, pop out each char for output. Example: fgh r yz MFE5008
Bracket Matching • Ensures that pairs of brackets are properly matched {a, (b+f[4])*3, d+f[5]} // properly matches (..)..) // too many closing brackets (..(..) // too many open brackets [..(..]..) // mismatched brackets MFE5008
Informal Procedure Initialise the stack to empty. For every char read. . if open bracket then push onto stack . if close bracket, then . topAndPop from the stack . if does not match then flag error . if non-bracket, skip the char read Example: {a, (b+f[4])*3, d+f[5]} MFE5008
Postfix Calculator • Computation of arithmetic expressions can be efficiently carried out in Postfix notation with the help of a stack Infix: arg1 op arg2 Prefix: op arg1 arg2 Postfix:arg1 arg2 op Example: 2*3+4, Postfix: 2 3 * 4 + 2*(3+4), Postfix: 1 3 4 + * MFE5008
Informal Procedure Initialise stack; For each item read, If it is an operand, push on the stack; If it is an operator, pop arguments from stack; perform operation; push result onto the stack Example: 2 3 4 + * MFE5008
Implementation of Stack (Linked-List) • Can use LinkedListItr as implementation • Top of Stack = Front of Linked-List StackLL list LinkedListItr head a0 a1 a2 a3 MFE5008
Implementation of Stack (Array) • Can use Array with a top index pointer as an implementation of stack StackAr arr top a b c d e f MFE5008
Example • Array implementation of a stack. page 300 • Linked list implementation of a stack, page 306 MFE5008
4. Queues • Queues implement the FIFO (First-In First-Out) policy • e.g., the printer/job queue enqueue(o) dequeue( ) Queue( ) isEmpty( ) getFront( ) MFE5008
Queue ADT Interface interface Stack { // returns a new empty stack Queue Queue( ); // returns true if empty boolean isEmpty( ); // enter o into stack void enqueue(Object o); // remove the first item void dequeue( ) throws underflow; // retrieve one item Object enquire( Object o); } MFE5008
Example to Use Queue ADT Queue q = new Queue ( ); q.enqueue ((Object) a); q.enqueue ((Object) b); q.enqueue ((Object) c); d = q.getFront( ); q.dequeue ( ); q.enqueue ((Object) e); q.dequeue( ); q d back front a b c e MFE5008
Applications of Queue • print queue • simulation • breath-first traversal of trees • checking palindrome MFE5008
Recognising Palindrome • Palindrome: A string which reads the same either left to right or right to left • e.g., radar and deed Procedure: . Given a string . Stack to reverse the character order of string . Queue to preserve the character order of string . Check if the two sequences are the same MFE5008
Implementation of Queue (Linked-List) Queue list addTail LinkedListItr current tail head a0 a1 a2 a3 MFE5008
Implementation of Queue (Array) • Can use Array with a front and back index pointer as an implementation of queue StackAr arr back a b c d e f front MFE5008
Java Implementation • Array implementation of a queue, page 347 • Linked list implementation of a queue, page 357 MFE5008
Priority Queue • Definition: a data structure that stores items along with a priority for each item. • The highest priority item is removed first insert(o) P. 364 PriotyQueue( ) getFront( ) MFE5008
Summary of Stacks and Queues • A stack is a Last-In/First-Out data structure • The Java Class Libraries also provide a stack class: java.util.Stack • Stacks have many uses in algorithms. • A queue is a First-In/First-Out data structure • A queue can be used to buffer data • http://java.sun.com/products/jdk/1.0.2/api/AllNames.html MFE5008