1 / 88

Data Structures Intro

Data Structures Intro. Linked Lists. Briana B. Morrison CSE 1302C Spring 2010. Topics. Collections Linked Lists Sorted Linked Lists Doubly Linked Lists Recursively Defined Linked Lists. Collections. A collection is an object that serves as a repository for other objects

ceri
Télécharger la présentation

Data Structures Intro

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Data Structures Intro Linked Lists Briana B. Morrison CSE 1302C Spring 2010

  2. Topics • Collections • Linked Lists • Sorted Linked Lists • Doubly Linked Lists • Recursively Defined Linked Lists

  3. Collections • A collection is an object that serves as a repository for other objects • A collection usually provides services such as adding, removing, and otherwise managing the elements it contains • Sometimes the elements in a collection are ordered, sometimes they are not • Sometimes collections are homogeneous, containing all the same type of objects, and sometimes they are heterogeneous

  4. Abstraction • Collections can be implemented in many different ways • Our data structures should be abstractions • That is, they should hide unneeded details • We want to separate the interface of the structure from its underlying implementation • This helps manage complexity and makes it possible to change the implementation without changing the interface

  5. Abstract Data Types • An abstract data type (ADT) is an organized collection of information and a set of operations used to manage that information • The set of operations defines the interface to the ADT • In one sense, as long as the ADT fulfills the promises of the interface, it doesn't matter how the ADT is implemented • Objects are a perfect programming mechanism to create ADTs because their internal details are encapsulated

  6. Dynamic Structures • A static data structure has a fixed size • This meaning is different from the meaning of the static modifier • Arrays are static; once you define the number of elements it can hold, the size doesn’t change • A dynamicdata structure grows and shrinks at execution time as required by its contents • A dynamic data structure is implemented using links

  7. Linked Lists • Previously we discussed the concepts of arrays and the ArrayList class. • Arrays and ArrayLists are examples of data structures, which are methodologies a program uses to store data in memory. • In some situations, the number of data items may dynamically increase or decrease as the program executes. • A Linked List is a data structure that shrinks and grows one object at a time, keeping the size of the list to a minimum at all times.

  8. student John Smith 40725 3.58 Object References • Recall that an object reference is a variable that stores the address of an object • A reference also can be called a pointer • References often are depicted graphically:

  9. John Smith 40725 3.57 Jane Jones 58821 3.72 References as Links • Object references can be used to create links between objects • Suppose a Student class contains a reference to another Student object

  10. studentList References as Links • References can be used to create a variety of linked structures, such as a linked list:

  11. Intermediate Nodes • The objects being stored should not be concerned with the details of the data structure in which they may be stored • For example, the Student class should not have to store a link to the next Student object in the list • Instead, we can use a separate node class with two parts: 1) a reference to an independent object and 2) a link to the next node in the list • The internal representation becomes a linked list of nodes

  12. Linked Lists • A linked list can be thought of as a chain of linked nodes. • A node is an object with two attributes: • data • the location of the next node in the chain 5

  13. Linked Lists • The data stored at each node can be primitive data types (int, char, ..) or objects (Book, Astronaut, …) • Here is an example of a list of Player objects. 7 Sarah Mario 5 Ajay Sonic 8 Gino Diablo 2 Jin Golf null head

  14. Linked Lists • To implement a linked list of Players, we will code three classes: • A Player class, encapsulating a player. • A PlayerNode, encapsulating a node. • A List class, encapsulating a linked list of Players.

  15. The Player Class • The Player class has three instance variables: • id, an int • name, a String • game, a String

  16. class Player { private int id; private string name; private string game; public Player(inti, String n, String g) { id = i; name = n; game = g; } public int ID { get { return id; } set { id = value; } } public String Name { get { return name; } set { name = value; } } public String Game { get { return game; } set { game = value; } } public bool Equals(Player p) { return (id == p.id && name.Equals(p.name) && game.Equals(p.game)); } public String toString() { return ("id: " + id + "\tname: " + name + "\tgame: " + game); } }

  17. The PlayerNode Class • The PlayerNode class has two instance variables: • player, a Player object reference • next, a PlayerNode object reference (the next node in the list)

  18. PlayerNode.cs class PlayerNode { private Player player; private PlayerNode next; public PlayerNode() { player = null; next = null; } public PlayerNode(Player p) { setPlayer(p); next = null; } public Player getPlayer() { return new Player(player.ID, player.Name, player.Game); } public PlayerNodegetNext() { return next; } public void setPlayer(Player p) { player = new Player(p.ID, p.Name, p.Game); } public void setNext(PlayerNode p) { next = p; } } }

  19. The LinkedListClass • Every LinkedListclass should have two instance variables: • head, a Node object reference (the first node in the list) • numberOfItems, an int (the number of items in the list, for convenience) • We declare the instance variables as protected so that our subclasses will inherit them.

  20. class LinkedList { protected PlayerNode head; protected intnumberOfItems; public LinkedList( ) { head = null; numberOfItems = 0; } public intgetNumberOfItems( ) { return numberOfItems; } public booleanisEmpty( ) { return ( numberOfItems == 0 ); } public String toString( ) { String listString = ""; PlayerNode current = head; for( inti = 0; i < numberOfItems; i++ ) { listString += current.getPlayer( ).toString( ) + "\n"; current = current.getNext( ); } return listString; } }

  21. The toString Method of the LL Class • ThetoStringmethod traverses the list (visits every node) and returns a String containing the data for all the objects in the list. public String toString( ) { String listString = ""; PlayerNode current = head; for( inti = 0; i < numberOfItems; i++ ) { listString += current.getPlayer( ).toString( ) + "\n"; current = current.getNext( ); } return listString; }

  22. Another Way to Code toString • Instead of using a for loop with the number of nodes, we can use a while loop and check for the end of the list (current == null) public String toString( ) { String listString = ""; PlayerNode current = head; while( current != null ) //check for last node { listString += current.getPlayer( ).toString( ) + "\n"; current = current.getNext( ); } return listString; }

  23. The DSExceptionClass • We are almost ready to code some meaningful methods of our linked list class, such as insert and delete. • We want our delete method to return the item just deleted. • But there will be instances where we cannot delete an item (empty list, item not found), and we do not want to return null. In these cases, we will throw an exception. Thus, we create our own exception class.

  24. DataStructureException public class DataStructureException: Exception { public DataStructureException( String s ) : base (s) { } }

  25. Linked List Functionality • At the minimum, we want to: • insert an item • delete an item • retrieve, or peek at, the contents of a node

  26. Linked List Functionality • There are many options for inserting an item in the list: at the beginning, at the end, at a certain position, before or after a certain item. We will implement insertion at the beginning of the list. • There are also many options for deleting an item from the list: at the beginning, at the end, at a certain position, based on a certain criteria. We will implement deletion based on the value of an instance variable; we have chosen id.

  27. Inserting at the Beginning of a List • Instantiate the new node (with data). • Attach the node to the beginning of the list. • Update head. • Update the number of items.

  28. Inserting at the Beginning of a List • Our original Linked List: 7 Sarah Mario 5 Ajay Sonic 8 Gino Diablo 2 Jin Golf null head

  29. Inserting at the Beginning of a List • Step 1: Instantiate a new node: PlayerNodepn = new PlayerNode( p ); // here, p is Player( 6, Steve, NFL ) 7 Sarah Mario 5 Ajay Sonic 8 Gino Diablo 2 Jin Golf null head 6 Steve NFL null

  30. Inserting at the Beginning of a List • Step 2: Attach the new node to the beginning of the list: pn.setNext( head ); 7 Sarah Mario 5 Ajay Sonic 8 Gino Diablo 2 Jin Golf 6 Steve NFL null head

  31. Inserting at the Beginning of a List • Step 3: Update head: head = pn; 7 Sarah Mario 5 Ajay Sonic 8 Gino Diablo 2 Jin Golf 6 Steve NFL null head

  32. Deleting from a Linked List • Locate the node to delete. • There are two cases: • The node is in the middle or at the end of the list. • The node is the head node. • In the second case, we need to update head. • Update the number of items (if successful).

  33. Deleting in the Middle or the End of a List • Before deleting the Player whose id is 8: 7 Sarah Mario 5 Ajay Sonic 8 Gino Diablo 2 Jin Golf null head previous current

  34. Deleting in the Middle/End of a List • Connect previous to the node after current: previous.setNext( current.getNext( ) ); • current is now unreachable, and is deleted. 7 Sarah Mario 5 Ajay Sonic 8 Gino Diablo 2 Jin Golf null head previous current

  35. Deleting at the Beginning of a List • Before deleting the Player whose id is 7: 7 Sarah Mario 5 Ajay Sonic 8 Gino Diablo 2 Jin Golf null head current

  36. Deleting at the Beginning of a List • Update head: head = head.getNext( ); • current is now unreachable, and is deleted. 7 Sarah Mario 5 Ajay Sonic 8 Gino Diablo 2 Jin Golf null current head

  37. Common Error Traps • When traversing a list and calling a method with a node reference, be sure that the node reference is not null. Calling a method with a null node reference will generate a NullPointerException at runtime. • Because compound expressions are evaluated left to right, if a compound logical expression uses an object reference to call a method, check whether the object reference is null in the first expression.

  38. Software Engineering Tips • Do not provide an accessor or mutator (or property) for the head node instance variable of the linked list. This will protect the head node from being accessed or changed outside the class. • Similarly, do not include a mutator method for the number of items in the list. Only the insert and delete methods of the linked list class should alter the number of items.

  39. More Software Engineering Tips • Provide a toString method that traverses the list. This is helpful at the debugging stage when testing other methods, in particular insert and delete. • Do not return an object reference to an item still in the list. Instead, return a reference to a copy of that item.

  40. Testing a Linked List Class • When testing a linked list class, be sure to test all possibilities. • Insert: • inserting into an empty list • inserting into a nonempty list • Delete: • attempting to delete from an empty list • attempting to delete an item not in the list • deleting the first item in the list • deleting the last item in the list • deleting an item in the middle of the list.

  41. Sorted Linked List • For some applications, it may be desirable for a Linked List to be sorted. • The items can be sorted based on the value of one of their instance variables, called a key. • A Linked List that stores its items in ascending (or descending) order according to a key value is called a Sorted Linked List. • For example, for a Sorted Linked List of Player objects, we could use the key id. • Without loss of generality, we will consider a list sorted in ascending order.

  42. Sorted Linked Lists • Here is an example of a sorted linked list of Player objects (the key is id ): 2 Jin Golf 5 Ajay Sonic 7 Sarah Mario 8 Gino Diablo null head

  43. SortedLinkedListMethods

  44. Inserting in a Sorted Linked List • When inserting an item in a sorted linked list, we must keep the list sorted; that is, after insertion is performed, the list is still sorted. • If the key value of the item to be inserted is smaller than all the key values in the list, then we insert the item at the beginning of the list. This operation is identical to our previous insertion in a linked list. • Otherwise, we will insert the item somewhere in the middle or at the end of the list.

  45. Inserting in the Middle or at the End of a Sorted Linked List • Instantiate the new node. • Traverse the list to identify the location to insert the new node. Call the node before previous, and the node after current. • Attach the new node to current. • Attach previous to the new node. • Update the number of items.

  46. Inserting in the Middle or at the End of a Sorted Linked List • Our original linked list: 2 Jin Golf 5 Ajay Sonic 7 Sarah Mario 8 Gino Diablo null head

  47. Inserting in the Middle or at the End of a Sorted Linked List • Step 1: Instantiate a new node: PlayerNode pn = new PlayerNode( p ); // here, p is Player( 6, Steve, NFL ) 2 Jin Golf 5 Ajay Sonic 7 Sarah Mario 8 Gino Diablo null head 6 Steve NFL null pn

  48. Inserting in the Middle or at the End of a Sorted Linked List • Step 2: Connect pn to current: pn.setNext( current ); 2 Jin Golf 5 Ajay Sonic 7 Sarah Mario 8 Gino Diablo null previous current head 6 Steve NFL pn

  49. Inserting in the middle or at the end of a Sorted Linked List • Step 3: Connect previous to pn: previous.setNext( pn ); 2 Jin Golf 7 Sarah Mario 8 Gino Diablo 5 Ajay Sonic null previous current head 6 Steve NFL pn

More Related