Linked Lists, Queues, Stacks

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

6-1 6 Stack ADTs Stack concepts. Stack applications. A stack ADT: requirements, contract. Implementations of stacks: using arrays, linked lists. Stacks.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Queue ADTs Queue concepts. Queue applications. A queue ADT: requirements, contract. Implementations of queues: using arrays, linked lists.
7 Queue ADTs  Queue concepts  Queue applications  A queue ADT: requirements, contract  Implementations of queues: using arrays and linked-lists  Queues.
9-1 9 Queue ADTs Queue concepts. Queue applications. A queue ADT: requirements, contract. Implementations of queues: using arrays, linked lists. Queues.
7-1 7 Queue ADTs Queue concepts. Queue applications. A queue ADT: requirements, contract. Implementations of queues: using arrays, linked lists. Queues.
4 Linked-List Data Structures  Linked-lists: singly-linked-lists, doubly-linked-lists  Insertion  Deletion  Searching © 2008 David A Watt, University.
Data Structures 4 Lists and Linked List Data Structures Prof A Alkhorabi.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
1 CSCD 326 Data Structures I Stacks. 2 Data Type Stack Most basic property: last item in (most recently inserted) is first item out LIFO - last in first.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Stacks, Queues & Deques CSC212.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
TCSS 342, Winter 2005 Lecture Notes
Implementing and Using Stacks
1 Lecture 26 Abstract Data Types – IV Overview  The List ADT  Implementing Stacks as Linked List  Linked List Implementation of Queues .  Preview:
Stacks, Queues, and Deques
Stacks, Queues, and Deques
Data Structures Using C++ 2E
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Chapter 7 Stacks I CS Data Structures I COSC 2006 April 22, 2017
SAK 3117 Data Structures Chapter 6: LINKED LISTS.
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
6 Stack ADTs  Stack concepts  Stack applications  Stack ADTs: requirements, contracts  Implementations of stacks: using arrays and linked-lists  Stacks.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
7.2 Priority Queue ADTs Priority queue concepts
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
HIT2037- HIT6037 Software Development in Java 22 – Data Structures and Introduction.
CSC 211 Data Structures Lecture 13
10 Binary-Search-Tree Data Structure  Binary-trees and binary-search-trees  Searching  Insertion  Deletion  Traversal  Implementation of sets using.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
4-1 4 Linked List Data Structures Linked lists: singly-linked and doubly-linked. Insertion. Deletion. Searching. © 2001, D.A. Watt and D.F. Brown.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
List Interface and Linked List Mrs. Furman March 25, 2010.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
1 Chapter 4 Unordered List. 2 Learning Objectives ● Describe the properties of an unordered list. ● Study sequential search and analyze its worst- case.
Click to edit Master text styles Stacks Data Structure.
Binary Tree Data Structures Binary trees and binary search trees. Searching. Insertion. Deletion. Traversal. Implementation of sets using BSTs.
Prefix notation in action
Chapter 16: Linked Lists.
C++ Programming:. Program Design Including
The List ADT.
Data Structure By Amee Trivedi.
Stacks Chapter 5.
Data Structures and Design in Java © Rick Mercer
Marcus Biel, Software Craftsman
KF5008 Collections(2) Dr Nick Dalton.
The Tree Data Structure
CE 221 Data Structures and Algorithms
Lists CS 3358.
Csc 2720 Data structure Instructor: Zhuojun Duan
Chapter 20 Lists, Stacks, Queues, and Priority Queues
Stacks.
Introduction to Data Structures
Stacks and Queues.
Stacks.
Stacks, Queues, and Deques
Data Structures ADT List
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
Stack A data structure in which elements are inserted and removed only at one end (called the top). Enforces Last-In-First-Out (LIFO) Uses of Stacks Evaluating.
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Stacks.
More Data Structures (Part 1)
Stacks, Queues, and Deques
8 List ADTs List concepts. List applications.
Presentation transcript:

Linked Lists, Queues, Stacks Insertion & Searching ArrayList Vs LinkedList Stack concepts, applications, example & contract Queue

Linked lists A linked list consists of a sequence of nodes connected by links, plus a header. Each node (except the last) has a successor, and each node (except the first) has a predecessor. Each node contains a single element (object or value), plus links to its successor and/or predecessor. ant bat cat header node element link null link ant bat cat

Singly-linked lists A singly-linked list (SLL) consists of a sequence of nodes, connected by links in one direction only. Each SLL node contains a single element, plus a link to the node’s successor (or a null link if the node has no successor). An SLL header contains a link to the SLL’s first node (or a null link if the SLL is empty). pig dog rat cat dog

Insertion Problem: Insert a new element at a given point in a linked list. Four cases to consider: insertion in an empty linked list; insertion before the first node of a nonempty linked list; insertion after the last node of a nonempty linked list; insertion between nodes of a nonempty linked list. The insertion algorithm needs links to the new node’s successor and predecessor.

SLL insertion (1) SLL insertion algorithm: To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: 2.1. Set node ins’s successor to first. 2.2. Set first to ins. 3. If the insertion point is after the node pred: 3.1. Set node ins’s successor to node pred’s successor. 3.2. Set node pred’s successor to ins. 4. Terminate.

SLL insertion (2) Animation (insertion before first node): ant bat cat first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: 2.1. Set node ins’s successor to first. 2.2. Set first to ins. 3. If the insertion point is after the node pred: 3.1. Set node ins’s successor to node pred’s successor. 3.2. Set node pred’s successor to ins. 4. Terminate. ant bat cat first ins To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: 2.1. Set node ins’s successor to first. 2.2. Set first to ins. 3. If the insertion point is after the node pred: 3.1. Set node ins’s successor to node pred’s successor. 3.2. Set node pred’s successor to ins. 4. Terminate. ant bat cat first ins To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: 2.1. Set node ins’s successor to first. 2.2. Set first to ins. 3. If the insertion point is after the node pred: 3.1. Set node ins’s successor to node pred’s successor. 3.2. Set node pred’s successor to ins. 4. Terminate. bat cat first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: 2.1. Set node ins’s successor to first. 2.2. Set first to ins. 3. If the insertion point is after the node pred: 3.1. Set node ins’s successor to node pred’s successor. 3.2. Set node pred’s successor to ins. 4. Terminate. ant bat cat first ins To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: 2.1. Set node ins’s successor to first. 2.2. Set first to ins. 3. If the insertion point is after the node pred: 3.1. Set node ins’s successor to node pred’s successor. 3.2. Set node pred’s successor to ins. 4. Terminate.

SLL insertion (3) Animation (insertion after intermediate node): dog fox first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: 2.1. Set node ins’s successor to first. 2.2. Set first to ins. 3. If the insertion point is after the node pred: 3.1. Set node ins’s successor to node pred’s successor. 3.2. Set node pred’s successor to ins. 4. Terminate. eel dog fox first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: 2.1. Set node ins’s successor to first. 2.2. Set first to ins. 3. If the insertion point is after the node pred: 3.1. Set node ins’s successor to node pred’s successor. 3.2. Set node pred’s successor to ins. 4. Terminate. eel pred ins dog fox first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: 2.1. Set node ins’s successor to first. 2.2. Set first to ins. 3. If the insertion point is after the node pred: 3.1. Set node ins’s successor to node pred’s successor. 3.2. Set node pred’s successor to ins. 4. Terminate. eel pred ins dog fox first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: 2.1. Set node ins’s successor to first. 2.2. Set first to ins. 3. If the insertion point is after the node pred: 3.1. Set node ins’s successor to node pred’s successor. 3.2. Set node pred’s successor to ins. 4. Terminate. pred dog fox first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: 2.1. Set node ins’s successor to first. 2.2. Set first to ins. 3. If the insertion point is after the node pred: 3.1. Set node ins’s successor to node pred’s successor. 3.2. Set node pred’s successor to ins. 4. Terminate. eel pred ins

Searching (1) Problem: Search for a given target value in a linked list. Unsorted SLL linear search algorithm: To find which (if any) node of the SLL headed by first contains an element equal to target: 1. For each node curr in the SLL headed by first, repeat: 1.1. If target is equal to node curr’s element, terminate with answer curr. 2. Terminate with answer none. DLL linear search is similar, except that we can search from last to first if preferred.

Searching (2) Analysis (counting comparisons): Let n be the SLL’s length. If the search is successful: Average no. of comparisons = n /2 (half the list) If the search is unsuccessful: No. of comparisons = n In either case, time complexity is O(n).

ArrayList Vs LinkedList An arraylist uses an array for internal storage. This means it's fast for random access (e.g. get me element 99), because the array index gets you right to that element. Adding and deleting at the start or middle of the arraylist would be slow, because all the later elements have to copied forward or backward. ArrayList would also give a performance issue when the internal array fills up. The arrayList has to create a new array and copy all the elements to it.

ArrayList Vs LinkedList (2) A linkedList is made up of a chain of nodes. Linked lists are slow when it comes to random access. Accessing element 99 means you have to traverse either forward from the beginning or backward from the end (depending on whether 99 is less than or greater than half the list size), calling next or previous, until you get to that element. Linked lists are fast for inserts and deletes anywhere in the list, since all you do is update a few next and previous pointers of a node.

linkedList Example import java.util.*; public class LinkedListDemo { public static void main(String[] args) {   LinkedList<String> myList=new LinkedList<String>();   myList.add("a");   myList.add("b");   myList.add(“c”);   System.out.println(“Contents of list is " + myList);   System.out.println(“Size of the list is " +  myList.size());    myList.addFirst(“d”); System.out.println(“Contents of list is " + myList);   System.out.println(“Size of the list is "  + myList.size());

linkedList Example (ctd)        myList.addLast(“e");   System.out.println(“Contents of list is " + myList);   System.out.println(“Size of list is"  + myList.size());   myList.add(2,“f");   System.out.println(“Contents of list is " + myList);   System.out.println(“Size of list is" + myList.size()); myList.add(1,”g”);   System.out.println(“Contents of list is " + myList);   System.out.println(“size of list is “ + myList.size());  myList.remove(3);   System.out.println(“Contents of list is " + myList);   System.out.println(“Size of list is “ + myList.size());   } }

Stack concepts (1) A stack is a last-in-first-out sequence of elements. Elements can added (push) and removed (pop) only at one end (the top of the stack). The depth of stack is the number of elements it contains. An empty stack has depth zero.

Stack concepts (2) Illustration (stack of books): Initially: Moby Dick War & Peace Rob Roy Initially: Moby Dick War & Peace After removing a book: Moby Dick War & Peace Misérables After adding “Misérables”: Moby Dick War & Peace Misérables 2001 After adding “2001”:

Stack applications Interpreter (e.g., the Java Virtual Machine) maintains a stack containing intermediate results during evaluation of complicated expressions also containing arguments and return addresses for method calls and returns. Parser (e.g., a component of the Java compiler) maintains a stack containing symbols encountered during parsing.

Example: text-file reversal A text file is a sequence of (zero or more) lines. To reverse the order of these lines, we must store them in a first- in-last-out sequence. Text-file reversal algorithm: To output the lines of file in reverse order: 1. Make line-stack empty. 2. For each line read from file, repeat: 2.1. Add line to the top of line-stack. 3. While line-stack is not empty, repeat: 3.1. Remove a line from the top of line-stack into line. 3.2. Output line. 4. Terminate.

Example: bracketing (1) A phrase is well-bracketed if: for every left bracket, there is a later matching right bracket for every right bracket, there is an earlier matching left bracket the subphrase between a pair of matching brackets is itself well-bracketed. Examples and counter-examples (maths expressions): s  (s – a)  (s – b)  (s – c) (– b + [b2 – 4ac]) / 2a s  (s – a)  (s – b  (s – c) s  (s – a)  s – b)  (s – c) (– b + [b2 – 4ac)] / 2a well-bracketed well-bracketed ill-bracketed ill-bracketed ill-bracketed

Example: bracketing (2) Bracket matching algorithm: checks for matches of (), [] or {}. To test whether phrase is well-bracketed: 1. Make bracket-stack empty. 2. For each symbol sym in phrase (scanning left to right), repeat: 2.1. If sym is a left bracket: 2.1.1. Add sym to the top of bracket-stack. 2.2. If sym is a right bracket: 2.2.1. If bracket-stack is empty, terminate with false. 2.2.2. Remove a bracket from the top of bracket-stack into left. 2.2.3. If left and sym are not matched brackets, terminate with false. 3. Terminate with true if bracket-stack is empty, or false otherwise.

Stack ADT: requirements It must be possible to make a stack empty. It must be possible to add (‘push’) an element to the top of a stack. It must be possible to remove (‘pop’) the topmost element from a stack. It must be possible to test whether a stack is empty. It should be possible to access the topmost element in a stack without removing it.

Stack ADT: contract (1) Possible contract, expressed as a Java interface*: public interface Stack { // Each Stack object is a stack whose elements are objects. /////////////// Accessors /////////////// public boolean empty(); // Return true if and only if this stack is empty. public Object peek(); // Return the element at the top of this stack. * an interface is a data type that requires implementing, it’s a class that contains only abstract methods and/or constants – it provides a specification – from programming 2

Stack ADT: contract (2) Possible contract (continued): ///////////// Transformers ///////////// public void clear (); // Make this stack empty. public void push(Object elem); // Add elem as the top element of this stack. public Object pop(); // Remove and return the element at the top of this stack. }

Stacks in the Java class library Java java.util.Stack class does this, but has no clear() function However, the java.util.LinkedList class also provides all the Stack operations clear() is LinkedList clear(), empty() is isEmpty(), peek() is getLast(), push() is addLast(), pop() is removeLast(). import java.util.LinkedList; LinkedList bookStack = new LinkedList(); bookStack.addLast("Moby Dick"); bookStack.addLast("War & Peace"); bookStack.addLast("Rob Roy"); System.out.println(bookStack.removeLast());

Queue concepts (1) A queue is a first-in-first-out sequence of elements. Elements can added only at one end (the rear of the queue) and removed only at the other end (the front of the queue). The length of a queue is the number of elements it contains. An empty queue has length zero.

Queue concepts (2) Illustration (queue of persons): BUS STOP

Queue applications Print server Disk driver maintains a queue of print jobs. Disk driver maintains a queue of disk input/output requests. Scheduler (e.g., in an operating system) maintains a queue of processes awaiting a slice of machine time. Traffic simulation Maintains many queues of vehicles

Example: demerging (1) Consider a file of person records, each of which contains a person’s name, gender, date-of-birth, etc. The records are sorted by date-of-birth. We are required to rearrange the records such that females precede males but they remain sorted by date-of- birth within each gender group. Bad idea: use a sorting algorithm. Time complexity is O(n log n) at best. Good idea: use a demerging algorithm. Time complexity is O(n).

Example: demerging (2) Demerging algorithm: To rearrange a file of person records such that females precede males but their order is otherwise unchanged: 1. Make queues females and males empty. 2. Until the input file is empty, repeat: 2.1. Let p be the next person read in from the file. 2.2. If p is female, add p to the rear of females. 2.3. If p is male, add p to the rear of males. 3. Until females is empty, repeat: 3.1. Write out the person removed from the front of females. 4. Until males is empty, repeat: 4.1. Write out the person removed from the front of males. 5. Terminate.

Queue ADT: requirements It must be possible to make a queue empty. It must be possible to test whether a queue is empty. It must be possible to obtain the length of a queue. It must be possible to add an element at the rear of a queue. It must be possible to remove the front element from a queue. It must be possible to access the front element in a queue without removing it.

Queue ADT: contract (1) Possible contract, expressed as a Java interface: public interface Queue { // Each Queue object is a queue whose elements are objects. /////////////// Accessors /////////////// public boolean isEmpty (); // Return true if and only if this queue is empty. public int size (); // Return this queue’s length. public Object getFirst (); // Return the element at the front of this queue.

Queue ADT: contract (2) Possible contract (continued): /////////////// Transformers /////////////// public void clear (); // Make this queue empty. public void addLast (Object elem); // Add elem as the rear element of this queue. public Object removeFirst (); // Remove and return the front element of this queue. }

Queue interface public interface Queue<E> extends Collection<E> { E element(); boolean offer(E o); E peek(); E poll(); E remove(); }

Queue Interface continued Each Queue method exists in two forms: one throws an exception if the operation fails the other returns a special value (either null or false, depending on the operation). Queue Interface Structure   Throws exception Returns special value Insert add(e) offer(e) Remove remove() poll() Examine element() peek()

Queues in the Java class library The java.util.LinkedList class provides all the Queue operations, for example import java.util.LinkedList; LinkedList<String> queue = new LinkedList<String>(); queue.addLast("Homer"); queue.addLast("Marge"); queue.addLast("Bart"); queue.addLast("Lisa"); queue.addLast("Maggie"); System.out.println(queue.removeFirst());