1/26 COP 3540 Data Structures with OOP Chapter 5 - Part 2 Linked Lists Abstract Data Types and Sorted Lists.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

1/27 COP 3540 Data Structures with OOP Chapter 5 Linked Lists.
DATA STRUCTURES USING C++ Chapter 5
Chapter 24 Lists, Stacks, and Queues
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
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.
Circular Linked List. Agenda  What is a Circularly linked list  Why a Circular Linked List  Adding node in a new list  Adding node to list with nodes.
COP3538 – Data Structures Using OOP Chapter 4 – Stacks and Queues.
CS 106 Introduction to Computer Science I 12 / 06 / 2006 Instructor: Michael Eckmann.
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.
CS 307 Fundamentals of Computer Science 1 Abstract Data Types many slides taken from Mike Scott, UT Austin.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
Linked Lists. Anatomy of a linked list A linked list consists of: –A sequence of nodes abcd Each node contains a value and a link (pointer or reference)
CS 106 Introduction to Computer Science I 12 / 11 / 2006 Instructor: Michael Eckmann.
Stacks, Queues, and Deques
Stacks, Queues, and Deques. 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.
Stacks, Queues, and Deques
Object Oriented Data Structures
1 / 23 COP 3540 Data Structures with OOP Chapter 4 Stacks and Queues.
Chapter 3 Introduction to Collections – Stacks Modified
9/17/20151 Chapter 12 - Heaps. 9/17/20152 Introduction ► Heaps are largely about priority queues. ► They are an alternative data structure to implementing.
October 18, Algorithms and Data Structures Lecture V Simonas Šaltenis Nykredit Center for Database Research Aalborg University
SAK 3117 Data Structures Chapter 6: LINKED LISTS.
Chapter 3 List Stacks and Queues. Data Structures Data structure is a representation of data and the operations allowed on that data. Data structure is.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
1 COP 3538 Data Structures with OOP Chapter 8 - Part 2 Binary Trees.
Lists ADT (brief intro):  Abstract Data Type  A DESCRIPTION of a data type  The data type can be anything: lists, sets, trees, stacks, etc.  What.
Data Structures Week 5 Further Data Structures The story so far  We understand the notion of an abstract data type.  Saw some fundamental operations.
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.
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
Chapter 9 (modified) Abstract Data Types and Algorithms Nell Dale John Lewis.
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
Data structures Abstract data types Java classes for Data structures and ADTs.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
Linked List. Background Arrays has certain disadvantages as data storage structures. ▫In an unordered array, searching is slow ▫In an ordered array, insertion.
The List ADT Definition A list is a collection of objects, called nodes, connected in a chain by links. There may or may not be an ordering relationship.
Linked List. Iterators Operation to find a link, deleting, and inserting before or after a specified link, also involve searching through the list to.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Linked Lists © John Urrutia 2013, All Rights Reserved1.
Introduction to Data Structures and Algorithms
Ordered Linked Lists using Abstract Data Types (ADT) in Java Presented by: Andrew Aken.
Computer Science Department Data Structures and Algorithms Queues Lecture 5.
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
M180: Data Structures & Algorithms in Java Linked Lists Arab Open University 1.
1 COP 3540 Data Structures with OOP Chapter 5 - Part 3 Linked Lists Doubly-Linked Lists and Iterators.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
LINKED LISTS.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
Linked List First next Data Linked List Link next Data Link next Data Link next Data Link Null.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
The List ADT.
Data Structures Interview / VIVA Questions and Answers
COP 3538 Data Structures with OOP
CMSC 341 Lecture 5 Stacks, Queues
Data Structures ADT List
Introduction to Data Structure
Lists.
Presentation transcript:

1/26 COP 3540 Data Structures with OOP Chapter 5 - Part 2 Linked Lists Abstract Data Types and Sorted Lists

2/26 Abstract Data Types  A wonderful way to deal with data structures.  An ADT is a way of looking at a data structure focusing on what it does and NOT how it does whatever it is supposed to do.  We implement an ADT  Stacks and Queues are examples of ADTs.  They are ‘concepts’ ; logical data structures.  Let’s first look how we can have a linked list that implements a stack.

3/26 A Stack Implemented by a Linked List  Can use an array, but no chance to extend it.  Basic operations: push() and pop() implemented as  arr[++top] = newdata; and returnedData = arr[top--];  Indexes are checked for stack overflow and stack underflow and then adjusted as shown.  For a Stack: implemented as a linked list, we have  theList.insertFirst(data) to add an element onto the stack (looks like a ‘push’)  Retrieved data = theList.deleteFirst(). (looks like a pop)  The important things: user calls push() and pop() for his/her stack operations and has no knowledge whether the logical stack is implemented as a physical array or as a physical linked list!

4/26 class LinkStackApp { public static void main(String[] args) { LinkStack theStack = new LinkStack(); // makes one stack object // We know nothing about the stack’s implementation from declaration. theStack.push(20 ); // push items theStack.push(40); theStack.displayStack(); // display stack theStack.push(60); // push items All generic at this point; abstract! theStack.push(80); theStack.displayStack(); // display stack theStack.pop(); // pop items theStack.pop(); theStack.displayStack(); // display stack } // end main() } // end class LinkStackApp all standard stack operations!! Client Application

5/26 class Link (objects of this class are the nodes themselves!) { public long dData; // data item public Link next; // next link in list; note: single link. // public Link(long dd) // constructor { dData = dd; } // public void displayLink() // display ourself { System.out.print(dData + " "); } } // end class Link // Note: this is really only the data (and the link) and not the most important methods… No Changes here…just the nodes…

6/26 class LinkStack { private LinkList theList;  =============================== // public LinkStack() // constructor { theList = new LinkList(); } // public void push(long j) // put item on top of stack { theList.insertFirst(j); } // public long pop() // take item from top of stack { return theList.deleteFirst(); } // public boolean isEmpty() // true if stack is empty { return ( theList.isEmpty() ); } // public void displayStack() { System.out.print("Stack (top-->bottom): "); theList.displayList(); } // } // end class LinkStack Client made an object of this class. This is the Interface to the implementation Can see a generic ‘push’ and ‘pop’ etc…. User sees the headers; not the implementation. See some implementation via the constructor where a linked list is created.

7/26 class LinkList { private Link first; // ref to first item on list public LinkList() // constructor { first = null; } // no items on list yet public boolean isEmpty() // true if list is empty { return (first==null); } public void insertFirst(long dd) // insert at start of list { // make new link Link newLink = new Link(dd); newLink.next = first; // newLink --> old first first = newLink; // first --> newLink //can you draw these steps??? } public long deleteFirst() // delete first item insertion part { // (assumes list not empty) deletion part too Link temp = first; // save reference to link first = first.next; // delete it: first-->old next return temp.dData; // return deleted link //can you draw these steps??? } public void displayList() { Link current = first; // start at beginning of list while(current != null) // until end of list, { current.displayLink(); // print data current = current.next; // move to next link } System.out.println(""); } // end class LinkList Here’s the linked list implementation! Here is your control class for the Linked List – your ‘collection class,’ if you will” Note the methods and what they operate on!! Note: the push is implemented via insertFirst() The pop is implemented via deleteFirst(). which are linked list operations. Logical operations implemented on physical structures

8/26 Discussion of Stack implemented with a Linked List  In the LinkStackApp, we pushed two items onto the stack  Displayed the stack  Pushed two more items  Displayed stack again  Popped two items  Displayed the remaining stack.  Design: LinkStackApp  LinkStack  LinkList  Link.  Beautiful part: When client calls push() or pop(), generic stack operations, s/he has no idea HOW the stack is implemented!!

9/26 A Queue Implemented by a Linked List  Same song, second verse.  Idea is to have operations  insert() and  remove() (both logical queue operations…)  that are meaningful to the client but yet do NOT reveal the design and implementation of those operations.  Consider the following Java code:

10/26 class LinkQueueApp (our Main) { public static void main(String[] args) { LinkQueue theQueue = new LinkQueue(); // Could be used to create a number of queues! // We know nothing about the queue’s implementation theQueue.insert(20); // insert items theQueue.insert(40); theQueue.displayQueue(); // display queue theQueue.insert(60); // insert items theQueue.insert(80); theQueue.displayQueue(); // display queue theQueue.remove(); // remove items theQueue.remove(); theQueue.displayQueue(); // display queue } // end main() } // end class LinkQueueApp Client Application

11/26 // Here are our queue items…(nodes here) No changes here! (simply the nodes themselves) These are ‘entity’ classes; data classes; objects; class Link { //this is our queue data and stack data items suitably modified with two links for a queue object and one link for stack object. In program2, design one class called Queue and a second: Stack. (two links because we are building a doubly-linked list for the queues) public long dData; // data item public Link next; // next link in list // public Link(long d) // constructor { dData = d; } // public void displayLink() // display this link { System.out.print(dData + " "); } // } // end class Link

12/26 class LinkQueue { private FirstLastList theList; // public LinkQueue() // constructor { theList = new FirstLastList(); } // end constructor; make a 2-ended list // public boolean isEmpty() // true if queue is empty { return theList.isEmpty(); }// end IsEmpty() // public void insert(long j) // insert, rear of queue { theList.insertLast(j); }// end insert() // public long remove() // remove, front of queue { return theList.deleteFirst(); }// end remove() // public void displayQueue() { System.out.print("Queue (front-->rear): "); theList.displayList(); }// end displayQueue() } // end class LinkQueue See logical operation: insert(). See the implementation which is insertLast(). Queue goes right to left. Rear of queue is on right Front of queue is on left. Insert() in rear (right) Remove() from front (left) See drawings ahead… Here’s the Interface to the implementation This app made an object of this. This is interface to implementation: Collection Class; Driver…. LL_Control class. You will need one object of this type per queue (4)

13/26 class FirstLastList { private Link first; // reference to a Link - first item  private Link last; // reference to a Link - last item  public FirstLastList() { // constructor first = null; // no items on list yet last = null;// sets these reference values to null.  } public boolean isEmpty() // true if no links Here is the implementation { return first==null; } Here’s your queue. public void insertLast(long dd) { // insert at end of list (rear) Link newLink = new Link(dd); // make new link  creates object!! if( isEmpty() ) // if empty list, first = newLink; // first --> newLink else last.next = newLink; // old last --> newLink last = newLink; // newLink <-- last // adjusts rear where new node is added. Here’s the implementation! } Queue implemented via a public long deleteFirst() { // delete first link Linked List. long temp = first.dData; // (assumes non-empty list) if(first.next == null) // if only one item last = null; // null <-- last first = first.next; // first --> old next // adjusting new front as node is removed. return temp; } public void displayList() { Link current = first; // start at beginning while(current != null) // until end of list, { current.displayLink(); // print data current = current.next; // move to next link } System.out.println(""); } // end class FirstLastList starting off values:

14/ newLink last First = null Last = null First = newLink Last = newLink Initially: Add first link: Add next link: 123 newlink null 334 newLink 123 newlink null last.next = newLink; last.= newLink; last Note: insert() is into the rear of the queue. (This can be implemented either way: where the ‘rear’ is on the left…) Link newLink = new Link(dd); // make new link  creates object!! Front of Queue

15/26 Discussion of Queues Implemented via Linked Lists  Again, merely implementing a queue using a linked list data structure instead of an array.  Note that linkStack and linkQueue  stacks and queues are conceptual entities.  They are the interfaces to the real implementations.  Their implementations represent the physical realization of these conceptual entities.  Choice? Array or Linked List?  Speed is about the same.  Uncertain size  use linked list  (linked list is also more complex…)

16/26 Data Types and Abstraction  Abstract Data Types.  Primitives types: data with certain characteristics and sets of operations that can be performed on that data.  In the computer, there are bounds too on primitive data types due to the computer’s architecture. ( for positive ints; for neg ints)  User-defined data types (quantitative types) Some can represent numerical goodies consisting of primitive data types. (Complex numbers? (2+3i ) Rational numbers? 1/3) Operations must be specified. (no division by zero, etc.) Can/Must define their attributes and their operations  User-defined data types (non-quantitative types) Consists of user-defined data types / combinations and the user- defined operations permissible on them, like getCountry(), etc...  Data types are defined to hold certain arrangements of data and possess sets of operations acceptable/appropriate to the data.

17/26 Data Types and Abstraction  “Abstract”  the data description is considered apart from whatever implementation might be used to deal with it.  Classes are abstractions – apart from the individual objects.  In OOP, we have lots of ADTs. (Think stacks, queues, trees…)  Have descriptions of fields and methods  Contain NO details regarding these implementations. These are done on purpose to provide uniform interfaces (like push() and pop() and insert()… yet provide opportunity for specific implementations that are more appropriate is some instances.  A client has access to the methods (through the method interface) and how to invoke, and what to expect in return. (public void push (int i) )  A client is NOT shown how the methods are implemented.  Another example: in String objects, we do not know how ‘compareTo’ is actually implemented. We do know how it works, how to use it, and what to expect in return.

18/26 ADTs as a Design Tool (  Think country classes…)  Consider what it is you need to do with data.  Operations. What operations need to be performed on the data?  Access: How do you need to access it?  Do you need to access an element via key? in specific sorted order? First one in a list, last one in a list?  THEN decide on the ADT, whose definition is determined by the operations you need to perform on the data.  Decouple the specification of ADT from implementation.  Can change the implementation later!  This is its beauty! Can always improve implementation.  Naturally the underlying data structure must make the specified operations as efficient as possible.  Need sequential access? Perhaps a linked list.  Need random access? A linked list does not provide this. An array does if you know the index of the desired array element. Array can be sorted easily too.

19/26 Example of a Subsystem (Architectural Design)  Subsystem: Maintain Credit Profile Subsystem  Desired Operations:  Create New Profile  Change Profile  Delete Profile  Get Profile  Display Profile, …. (subsystem realizes the interface) Create_profile(); Change_profile(); Delete_profile(); Get_profile(); Display_profile(); With lots of connections / dependencies, etc. Maintain Credit Profile Subsystem MCPS - Int > These are the operations needed. Provided in interface. In a subsystem, implementation is provided inside subsystem, whose contents is not available to client. Interface, however, is.

20/26 SORTED Linked LISTS  Lists where items are in an order.  Sorted on some key value usually inside the node.  Can delete via a find() followed by a ‘logical’ delete()  Can have sorted list in same way as a sorted array.  Advantages of a sorted linked list over a sorted array  are those deficiencies found in the processing of arrays:  Speed of insertion: ( O(n) ) Find place for new item (‘same’ search time as array)  But to Insert in linked list: other items don’t need to be moved!!!)  Size of list the fact that the size of the list can expand almost indefinitely.  Disadvantage: Cannot do a binary search on a sorted linked list.

21/26 Java Code to Insert an item into a Sorted List Clearly, there must be a search algorithm to find the place where the new item should go. insert() routine is in book. (will look at this ahead…) Essentially it is a search routine to find the place to insert the new list item. Remember: when searching (with a goal of inserting or deleting) a singly-linked list, you MUST keep the location (reference) of ‘previous’ link when looking at a ‘current link.’ Not true for a doubly linked list next set of slides.

22/26 Additional Considerations  When inserting into a sorted list, new entry may well be placed logically somewhere within the list. Physically? We don’t know / care where…  Boundary Conditions:  But it may be the new ‘first’ element in the list.  Could also be ‘last’  Error Conditions:  May also be a duplicate!! (generally not wanted)  May not be able to find link if we are to ‘change’  Let’s look at the unique code:

23/26 class SortedList { private Link first; // ref to first item public SortedList() // constructor { first = null; } public boolean isEmpty() // true if no links { return (first==null); } public void insert(long key) { // insert, in order Link newLink = new Link(key); // make new link Link previous = null; // start at first Link current = first; while(current != null && key > current.dData) { // or key > current, previous = current;// note: sort is ‘descending’ current = current.next; // go to next item } // end while code. Of interest. if(previous==null) // at beginning of list Must find the right spot!! first = newLink; // first --> newLink else // not at beginning { previous.next = newLink; // old prev --> newLink newLink.next = current; // newLink --> old currnt } // end else } // end insert() public Link remove() { // return & delete first link // (assumes non-empty list) Link temp = first; // save first first = first.next; // delete first return temp; // return value } public void displayList() { System.out.print("List (first-->last): "); Link current = first; // start at beginning of list while(current != null) { // until end of list, current.displayLink(); // print data current = current.next; // move to next link } System.out.println(""); } } // end class SortedList

24/26 Efficiency of Sorted Linked Lists  Inserting and deleting any item in a sorted linked list requires O(n) comparisons (that is a number of comparisons directly proportional to the number of items IN the list) with n/2 being the average.  The smallest (minimum item) can be found or deleted in O(1) time since it is in the beginning of the list. (or end of the list if you maintain ‘first’ and ‘last’ pointers.)  If access is frequently in the beginning, this is good and if inserting is not done a lot or the speed is not critical, sorted linked lists are pretty effective.  Using the notion of a sorted list, realize that a priority queue might be implemented by a sorted linked list.