1 / 119

Chapter 12: Lists

Chapter 12: Lists. Writing ListClasses Example: Infinite Precision Arithmetic Example: Sorting a Lsit Example: A Set Type Doubly Linked Lists Computer Security. Introduction. Dynamic data structure Grows and shrinks as program runs Example: Java’s standard Vector class Lists

sahkyo
Download Presentation

Chapter 12: Lists

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. Chapter 12: Lists Writing ListClasses Example: Infinite Precision Arithmetic Example: Sorting a Lsit Example: A Set Type Doubly Linked Lists Computer Security

  2. Introduction • Dynamic data structure • Grows and shrinks as program runs • Example: Java’s standard Vector class • Lists • Used often in everyday life (groceries, to-do, …) • Will also look at sets in this chapter • Dynamic data structures in later chapters • Stacks • Queues • Trees Programming and Problem Solving With Java

  3. Introduction • Characteristics of lists • There’s a first element • There’s a last element • All others have predecessor and successor • Operations on lists • Add element • Delete element • Search for element • Sort the elements Programming and Problem Solving With Java

  4. Writing List Classes: CharList • Character list class • Allows adding and deleting characters from either end • Operations • toString Returns contents in a string. • insertFirst Put new character value at beginning • insertLast Put new character value at end • empty Returns true if empty • removeFirst Remove node at beginning, return value • removeLast Remove node at end, return value Programming and Problem Solving With Java

  5. Writing List Classes: CharList • Short example • // Short demonstration of how to use the CharList • // class • import CharList; • public class DemoCharList • { • public static void main(String[] args) • { • CharList myCharList = new CharList(); • // Insert some characters • myCharList.insertFirst('i'); • myCharList.insertLast('!'); • myCharList.insertFirst('H'); • // Use the toString() method • System.out.println(myCharList); • // Remove character • System.out.println("Removed " • + myCharList.removeFirst()); • // Use the toString() method again • System.out.println(myCharList); • } • } [H i ! ] Removed H [i ! ] Programming and Problem Solving With Java

  6. Writing List Classes: CharList • Longer example (uses TextMenu class) • // This program lets you add characters onto • // either end of a linked list, and remove them from either • // end. It makes sure you don't try to remove characters • // from an empty list. This is a demonstration of how to use • // the CharList class. • import Keyboard; • import TextMenu; • import CharList; • public class CharListTest extends TextMenu • { • static final int ADD_FIRST_COMMAND = 1; • static final int ADD_LAST_COMMAND = 2; • static final int REMOVE_FIRST_COMMAND = 3; • static final int REMOVE_LAST_COMMAND = 4; • // Constructor - set up menu for the editor • public CharListTest() • { • super("Character List Menu"); • list = new CharList(); • addSelection("Add first", '1', ADD_FIRST_COMMAND); • addSelection("Add last", '2', ADD_LAST_COMMAND); • addSelection("Remove first", '3', REMOVE_FIRST_COMMAND); • addSelection("Remove last", '4', REMOVE_LAST_COMMAND); • addSelection("Quit", '5', TextMenu.QUIT); • } Programming and Problem Solving With Java

  7. Writing List Classes: CharList • // Event dispatcher • public int handleEvent(int event) • throws java.io.IOException • { • switch (event) • { • case ADD_FIRST_COMMAND: • list.insertFirst(Keyboard.readChar( • "Enter character to add to beginning: ")); • break; • case ADD_LAST_COMMAND: • list.insertLast(Keyboard.readChar( • "Enter character to add to end: ")); • break; • case REMOVE_FIRST_COMMAND: • if (list.empty()) • { • System.out.println("List is empty!"); • } • else • { • System.out.println("Removed " + list.removeFirst() • + " from beginning of list"); • } • break; • case REMOVE_LAST_COMMAND: • if (list.empty()) • { • System.out.println("List is empty!"); • } • else • { • System.out.println("Removed " + list.removeLast() • + " from end of list"); • } • break; • } • System.out.println("List is now: " + list); • return event; • } Programming and Problem Solving With Java

  8. Writing List Classes: CharList • // Instance variables • CharList list; • public static void main(String[] args) • throws java.io.IOException • { • CharListTest listExample = new CharListTest(); • listExample.run(); • } • } +--- Character List Menu --- | 1) Add first 2) Add last 3) Remove first | 4) Remove last 5) Quit | Enter selection: 1 Enter character to add to beginning: b List is now: [b ] +--- Character List Menu --- | 1) Add first 2) Add last 3) Remove first | 4) Remove last 5) Quit | Enter selection: 1 Enter character to add to beginning: a List is now: [a b ] +--- Character List Menu --- | 1) Add first 2) Add last 3) Remove first | 4) Remove last 5) Quit | Enter selection: 2 Enter character to add to end: c List is now: [a b c ] Programming and Problem Solving With Java

  9. Writing List Classes: CharList • CharList is linked structure: each character on the list keeps track of its successor • CharListNode is separate class • Space for the character • Reference to next character in list • Last node references null (special value) Programming and Problem Solving With Java

  10. Writing List Classes: CharList • CharListNode class • class CharListNode • { • // Constructor • public CharListNode(char item, CharListNode next) • { • setItem(item); • setNext(next); • } • // getItem: Returns the item value • public char getItem() { return item; } • // getNext: Returns the next item • public CharListNode getNext() { return next; } • // setItem: Sets the item to the given value • public void setItem(char item) • { • this.item = item; • } • // setNext: Sets the next item to the given object • public void setNext(CharListNode next) • { • this.next = next; • } • // Instance vaiables • private char item; • private CharListNode next; • } Programming and Problem Solving With Java

  11. Writing List Classes: CharList • CharList class • References first and last nodes of the list • Constructor • // Default constructor • public CharList() • { • first = null; • last = null; • numNodes = 0; • } Makes emptyCharList Programming and Problem Solving With Java

  12. Writing List Classes: CharList • Inserting a new node: insertFirst() • // insertFirst: Inserts a new item at the beginning of the list. • public void insertFirst(char item) • { • CharListNode newNode = new CharListNode(item, first); • numNodes++; • first = newNode; • if (last == null) • { • // Special case: An empty list. • // This new node is the last node in the list. • last = newNode; • } • } Programming and Problem Solving With Java

  13. Writing List Classes: CharList • Inserting a new node: insertLast() • // insertLast: Inserts a new item at the end of the list • public void insertLast(char item) • { • CharListNode newNode = new CharListNode(item, null); • numNodes++; • if (first == null) • { • // Special case: this node is the first node in the list. • first = newNode; • } • else • { • // General case: this is not the only node in the list. • // Make the last node point to this one and make this • // the new last node. • last.setNext(newNode); • } • last = newNode; • } Programming and Problem Solving With Java

  14. Writing List Classes: CharList • Removing a node:removeFirst() Programming and Problem Solving With Java

  15. Writing List Classes: CharList • Removing a node: removeFirst() • // removeFirst: Remove the first element from the list and • // return its value. If item is currentNode, • // then sets currentNode to next node, unless • // deleting the last node. In that case, sets • // currentNode to previous node. • // Note: The list cannot be empty • public char removeFirst() • { • Debug.assert(!empty(), • "CharList.removeFirst(): List is empty"); • CharListNode node = first; • // Remove the first node from the list. • first = first.getNext(); • if (empty()) • { • // Special case: this is the only node in the list. • last = null; • } • numNodes--; • // Return the value of the removed node. • return node.getItem(); • } Programming and Problem Solving With Java

  16. Writing List Classes: CharList • Removing a node:removeLast() Programming and Problem Solving With Java

  17. Writing List Classes: CharList • Removing a node: removeLast() • // removeLast: Remove the last element from the list and • // return its value. If item is currentNode, • // then sets currentNode to next node, unless • // deleting the last node. In that case, sets • // currentNode to previous node. • // Note: The list cannot be empty • public char removeLast() • { • Debug.assert(!empty(), "CharList.removeLast(): List is empty"); • CharListNode node = last, previousNode; • if (last == first) • { • // Special case: only one node in the list • last = first = null; • } • else • { • // General case: find second-to-last node • previousNode = first; • while (previousNode.getNext() != last) • { • previousNode = previousNode.getNext(); • } • // Make second-to-last the last node • previousNode.setNext(null); • last = previousNode; • } • numNodes--; • // Return the value of the removed node. • return node.getItem(); • } Programming and Problem Solving With Java

  18. Writing List Classes: CharList • empty(), count(), toString() • // empty: Returns true if the list is empty • public boolean empty() • { • return first == null; • } • // count: Returns the number of elements in the list • public int count() • { • return numNodes; • } • // toString: Returns a string representing the contents of • // the list • public String toString() • { • CharListNode node = first; • String result = "["; • while (node != null) • { • result = result + node.getItem() + " "; • node = node.getNext(); • } • return result + "]"; • } Programming and Problem Solving With Java

  19. Writing List Classes: CharList • Problems with the CharList class • Can’t tell if particular value in the list (without displaying the list and examining the output) • Can't insert a value in the middle • Can't remove a value from the middle • Can't traverse the list, except to display every element • Can't get a value from the list without removing it • Can't change a value in the list without removing it and inserting the new value • Can only store characters Programming and Problem Solving With Java

  20. A General List Class • Additional features over CharList: • Store into the middle (not just ends) • Remove from middle • Check whether a particular value is in the list • Get values of elements inside the list • Store any object -- not just characters • To store and retrieve elements from middle of list • Need way to refer to list position • Will add current node marker • Will have methods for moving current node marker Programming and Problem Solving With Java

  21. A General List Class • List operations • append: Attach another list to end • count: Return number of nodes • toString: Return String version of list’s contents • find: Search for value. If in list, set the current node there • get: Return value in current node • goFirst: Change current node to beginning • goLast: Change current node to end • goNext: Change current node to next node • goPrevious: Change current node to previous node • insert: Put new value after current node • insertFirst: Put new value at beginning Programming and Problem Solving With Java

  22. A General List Class • List operations (continued) • insertLast: Put new value at end • isDefined: Return true if current node defined • empty: Return true if list empty • isFirst: Return true if current node is first node • isLast: Return true if current node is last node • put: Change value of current node • remove: Remove current node, return its value • removeFirst: Remove node at beginning of the list, return its value • removeLast: Remove node at end of list, and return its value Programming and Problem Solving With Java

  23. A General List Class: Line Editor • Today, most editors are full-screen • Move cursor with keys or mouse • Type at position of cursor • Older style: line editor • Make changes to one line at a time • Must specify line to change with a command • Not as easy to use as full-screen editor • Much easier to write, though Programming and Problem Solving With Java

  24. A General List Class: Line Editor • Example of line editor: MS-DOS edlin C:\>edlin Hello.java New file *I 1:*class Hello 2:*{ 3:* public static void main(String[] args) 4:* { 5:* System.out.println("Hello!"); 6:* } 7:*} 8:*^C *1I 1:*// Says Hello 2:* 3:*^C *L 1: // Says Hello 2: 3:*class Hello 4: { 5: public static void main(String[] args) 6: { 7: System.out.println("Hello!"); 8: } 9: } *E C:\> Line commands Current line (markedwith *) Programming and Problem Solving With Java

  25. A General List Class: Line Editor • Will use List class to make line editor • Store each line in a list node • Commands • Show all lines with line numbers • Insert lines after a given line number • Delete a line • Quit the program • To insert lines • Type as many lines as desired • Type just period on line to end Programming and Problem Solving With Java

  26. A General List Class: Line Editor • Example run of line editor • +--- Edit Menu --- • | s) Show all lines i) Insert lines d) Delete a line • | q) Quit • | Enter selection: i • (Enter just a period to stop inserting lines) • : This is the first line in the editor. The • : editor is in insert mode. When a period is • : typed by itself, insert mode stops. • : . • +--- Edit Menu --- • | s) Show all lines i) Insert lines d) Delete a line • | q) Quit • | Enter selection: s • 1: This is the first line in the editor. The • 2: editor is in insert mode. When a period is • 3: typed by itself, insert mode stops. • +--- Edit Menu --- • | s) Show all lines i) Insert lines d) Delete a line • | q) Quit • | Enter selection: i • After which line: 2 • (Enter just a period to stop inserting lines) • : --- This is the new third line. --- • : . Programming and Problem Solving With Java

  27. A General List Class: Line Editor • Example run of line editor (continued) • +--- Edit Menu --- • | s) Show all lines i) Insert lines d) Delete a line • | q) Quit • | Enter selection: s • 1: This is the first line in the editor. The • 2: editor is in insert mode. When a period is • 3: --- This is the new third line. --- • 4: typed by itself, insert mode stops. • +--- Edit Menu --- • | s) Show all lines i) Insert lines d) Delete a line • | q) Quit • | Enter selection: d • Line to delete: 3 • +--- Edit Menu --- • | s) Show all lines i) Insert lines d) Delete a line • | q) Quit • | Enter selection: s • 1: This is the first line in the editor. The • 2: editor is in insert mode. When a period is • 3: typed by itself, insert mode stops. • +--- Edit Menu --- • | s) Show all lines i) Insert lines d) Delete a line • | q) Quit • | Enter selection: q • Are you sure you want to quit? (y/n): y Programming and Problem Solving With Java

  28. A General List Class: Line Editor • Design of the line editor program • Will use the TextMenu framework for menus • Will use the List class to store lines Programming and Problem Solving With Java

  29. A General List Class: Line Editor • Methods in EditApplication class • EditApplication(): Constructor, initializes menu • handleEvent(): Event dispatcher • goToLine(): Changes current line to user-specified line number • insertLines(): Prompts user for a line number, then prompts user for lines to insert after that. Stops when user enters line with just a period. • deleteLine(): Prompts user for a line number, then deletes that line • displayLines(): Display all lines Programming and Problem Solving With Java

  30. A General List Class: Line Editor • EditApplication constructor • // Constructor - set up menu for the editor • public EditApplication() • { • super("Edit Menu"); • editBuffer = new List(); • addSelection("Show all lines", 's', SHOW_COMMAND); • addSelection("Insert lines", 'i', INSERT_COMMAND); • addSelection("Delete a line", 'd', DELETE_COMMAND); • addSelection("Quit", 'q', TextMenu.QUIT); • } • EditApplication constants • static final int SHOW_COMMAND = 1; • static final int INSERT_COMMAND = 2; • static final int DELETE_COMMAND = 3; • EditApplication main() • public static void main(String[] args) • throws java.io.IOException • { • EditApplication editor = new EditApplication(); • editor.run(); • } Programming and Problem Solving With Java

  31. A General List Class: Line Editor • EditApplication handleEvent() • // Event dispatcher for the editor • public int handleEvent(int event) • throws java.io.IOException • { • switch (event) • { • case SHOW_COMMAND: • displayLines(); • break; • case INSERT_COMMAND: • insertLines(); • break; • case DELETE_COMMAND: • deleteLine(); • break; • case TextMenu.QUIT: • if (Keyboard.readChar( • "Are you sure you want to quit? (y/n)", "yn") != 'y') • { • event = TextMenu.CANCEL_QUIT; • } • break; • } • return event; • } Programming and Problem Solving With Java

  32. A General List Class: Line Editor • EditApplication insertLines() steps • Ask the user where to begin inserting new lines. • Move to that line in the list. • Read a line from the user. • As long as the line isn't just a period, do the following steps. • Insert the line into the list. • Move to the new line, so the next line will be inserted after it. • Read the next line from the user. Programming and Problem Solving With Java

  33. A General List Class: Line Editor • EditApplication insertLines() • // insertLines: Prompts user for a line number, then prompts • // user for lines to insert after that line. • // Stops when the user enters a line with just • // a period on it. • void insertLines() • throws java.io.IOException • { • String line; • if (!editBuffer.empty()) • { • goToLine(Keyboard.readInt("After which line: ", 1, • editBuffer.count())); • } • System.out.println( • "(Enter just a period to stop inserting lines)"); • line = Keyboard.readString(": "); • while (!line.equals(".")) • { • if (editBuffer.isDefined()) • { • editBuffer.insert(line); • editBuffer.goNext(); • } • else • { • editBuffer.insertFirst(line); • editBuffer.goFirst(); • } • line = Keyboard.readString(": "); • } • } Programming and Problem Solving With Java

  34. A General List Class: Line Editor • EditApplication gotoLine() • // goToLine: Changes the current line to a specific line number • // Note: lineNum must be in the range 1 to number of lines • // in buffer • void goToLine(int lineNum) • { • // Check precondition • Debug.assert(lineNum >= 1 && lineNum <= editBuffer.count(), • "EditApplication.goToLine(): Invalid line number"); • editBuffer.goFirst(); • for(int i = 1; i < lineNum; i++) • { • editBuffer.goNext(); • } • } Programming and Problem Solving With Java

  35. A General List Class: Line Editor • EditApplication deleteLine() steps • Ask the user which line to delete • Move to that line • Delete that line • EditApplication deleteLine() • // deleteLine: Prompts user for a line number, then deletes • // that line • void deleteLine() • throws java.io.IOException • { • if (editBuffer.empty()) • { • System.out.println("No lines"); • } • else • { • goToLine(Keyboard.readInt("Line to delete: ", 1, • editBuffer.count())); • editBuffer.remove(); • } • } Programming and Problem Solving With Java

  36. A General List Class: Line Editor • EditApplication displayLines() • // displayLines: Display all lines in the buffer • void displayLines() • { • int lineNumber = 0; • for(editBuffer.goFirst(); • editBuffer.isDefined(); • editBuffer.goNext()) • { • lineNumber++; • System.out.println(lineNumber + ": " + editBuffer.get()); • } • } • Shows how to use for statement to traverse elements of a list • Move to first line with goFirst() • Test whether past end of list with isDefined() • Move to next line with goNext() Programming and Problem Solving With Java

  37. A General List Class: Implementation • List is a container type • Holds elements of another type • Array is another container type • Common implementation of a container as a linked type • Class for each node of the container • Class for the container itself • Used this implementation with CharList • CharListNode • CharList • Will store an Object value in each node Programming and Problem Solving With Java

  38. A General List Class: Implementation • ListNode class • class ListNode • { • // Constructor • ListNode(Object item, ListNode next) • { • setItem(item); • setNext(next); • } • // getItem: Returns the item value • public Object getItem() { return item; } • // getNext: Returns the next item • public ListNode getNext() { return next; } • // setItem: Sets the item to the given value • public void setItem(Object item) • { • this.item = item; • } • // setNext: Sets the next item to the given object • public void setNext(ListNode next) • { • this.next = next; • } • // Instance variables • Object item; • ListNode next; • } Programming and Problem Solving With Java

  39. A General List Class: Implementation • List class structure • Instance variables • // Instance variables • int numNodes; // The number of nodes in the list • ListNode first, // Reference to the first node • last, // Reference to the last node • currentNode; // Reference to the current node Programming and Problem Solving With Java

  40. A General List Class: Implementation • List constructor • // Default constructor • public List() • { • first = null; • last = null; • currentNode = null; • numNodes = 0; • } • List insertFirst (similar to CharList) • // insertFirst: Inserts a new item at the beginning of the list. • public void insertFirst(Object item) • { • ListNode newNode = new ListNode(item, first); • numNodes++; • first = newNode; • if (last == null) • { • // Special case: An empty list. • // This new node is the last node in the list. • last = newNode; • } • } Programming and Problem Solving With Java

  41. A General List Class: Implementation • List insertLast (similar to CharList) • // insertLast: Inserts a new item at the end of the list • public void insertLast(Object item) • { • ListNode newNode = new ListNode(item, null); • numNodes++; • if (first == null) • { • // Special case: this node is the first node in • // the list. • first = newNode; • } • else • { • // General case: this is not the only node in the list. • // Make the last node point to this one and make • // this the new last node. • last.setNext(newNode); • } • last = newNode; • } Programming and Problem Solving With Java

  42. A General List Class: Implementation • List insert() • Puts new node after currentNode • Caller responsible for setting currentNode first • // insert: Inserts a new item after a node pointed to by • // currentNode. • // Note: currentNode must be defined • public void insert(Object item) • { • Debug.assert(isDefined(), • "List.insert(): currentNode undefined"); • ListNode newNode = new ListNode(item, currentNode.getNext()); • numNodes++; • currentNode.setNext(newNode); • if (currentNode == last) • { • // Special case: this is the new last node. • last = newNode; • } • } Programming and Problem Solving With Java

  43. A General List Class: Implementation • List put() • // put: Changes the value of the currentNode node to item • // Note: currentNode must be defined • public void put(Object item) • { • Debug.assert(isDefined(), • "List.put(): currentNode undefined"); • currentNode.setItem(item); • } • List get() • // get: Returns the value in the currentNode • // Note: currentNode must be defined • public Object get() • { • Debug.assert(isDefined(), • "List.get(): currentNode undefined"); • return currentNode.getItem(); • } Programming and Problem Solving With Java

  44. A General List Class: Implementation • List removeFirst() • Uses removeNode() helper method • // removeFirst: Remove the first element from the list and • // return its value. If item is currentNode, • // then sets currentNode to next node, • // unless deleting the last node. In that case, • // sets currentNode to previous node. • // Note: The list must not be empty • public Object removeFirst() • { • Debug.assert(!empty(), • "List.removeFirst(): List is empty"); • Object returnValue = first.getItem(); • removeNode(first, null); • return returnValue; • } Programming and Problem Solving With Java

  45. A General List Class: Implementation • List removeLast() • Uses removeNode() helper method • // removeLast: Remove the last element from the list • // and return its value. If item is • // currentNode, then sets currentNode • // to next node, unless deleting the last • // node. In that case, sets currentNode to • // previous node. • // Note: The list must not be empty • public Object removeLast() • { • Debug.assert(!empty(), • "List.removeLast(): List is empty"); • // Set last to node before last one • Object returnValue = last.getItem(); • removeNode(last, findPreviousNode(last)); • return returnValue; • } Programming and Problem Solving With Java

  46. A General List Class: Implementation • List remove() • // remove: Removes item referenced by currentNode, and • // returns its value. Sets currentNode to next • // node, unless deleting the last node. In that • // case, sets currentNode to previous node. • // Note: currentNode must be defined • public Object remove() • { • Debug.assert(isDefined(), • "List.remove(): currentNode undefined"); • Object returnValue = currentNode.getItem(); • removeNode(currentNode, • findPreviousNode(currentNode)); • return returnValue; • } • List append() • // append: Appends elements of the source list to this one • public void append(List source) • { • for (source.goFirst(); • source.isDefined(); • source.goNext()) • { • insertLast(source.get()); • } • } Programming and Problem Solving With Java

  47. A General List Class: Implementation • List find() • // find: If a particular value is in the list, sets • // currentNode to that node and returns true. • // Otherwise, leaves currentNode as it was and • // returns false. • public boolean find(Object data) • { • ListNode node = first; • // Find node containing the data value • while (node != null && !(node.getItem().equals(data))) • { • node = node.getNext(); • } • if (node == null) • { • return false; • } • currentNode = node; • return true; • } Programming and Problem Solving With Java

  48. A General List Class: Implementation • List goFirst() • // goFirst: Sets currentNode to beginning of list • public void goFirst() • { • currentNode = first; • } • List goList() • // goLast: Sets currentNode to end of list • public void goLast() • { • currentNode = last; • } • List goNext() • // goNext: Sets currentNode to next element in the list • // Note: currentNode must be defined • public void goNext() • { • Debug.assert(isDefined(), • "List.goNext(): currentNode undefined"); • currentNode = currentNode.getNext(); • } Programming and Problem Solving With Java

  49. A General List Class: Implementation • List goPrevious() • // goPrevious: Sets currentNode to previous element in • // the list • // Note: currentNode must be defined • public void goPrevious() • { • Debug.assert(isDefined(), • "List.goPrevious(): currentNode undefined"); • currentNode = findPreviousNode(currentNode); • } Programming and Problem Solving With Java

  50. A General List Class: Implementation • Removing a node Programming and Problem Solving With Java

More Related