chapter 12: lists

119
Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 12: Lists Writing ListClasses Example: Infinite Precision Arithmetic Example: Sorting a Lsit Example: A Set Type Doubly Linked Lists Computer Security

Upload: sahkyo

Post on 17-Jan-2016

36 views

Category:

Documents


0 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 12: Lists

Programming and Problem SolvingWith Java

Copyright 1999, James M. Slack

Chapter 12: ListsWriting ListClassesExample: Infinite Precision ArithmeticExample: Sorting a LsitExample: A Set TypeDoubly Linked ListsComputer Security

Page 2: Chapter 12: Lists

Programming and Problem Solving With Java 2

IntroductionDynamic data structure

Grows and shrinks as program runsExample: Java’s standard Vector class

ListsUsed often in everyday life (groceries, to-do, …)

Will also look at sets in this chapterDynamic data structures in later chapters

StacksQueuesTrees

Page 3: Chapter 12: Lists

Programming and Problem Solving With Java 3

IntroductionCharacteristics of lists

There’s a first elementThere’s a last elementAll others have predecessor and successor

Operations on listsAdd elementDelete elementSearch for elementSort the elements

Page 4: Chapter 12: Lists

Programming and Problem Solving With Java 4

Writing List Classes: CharListCharacter list class

Allows adding and deleting characters from either endOperations

toString Returns contents in a string. insertFirst Put new character value at beginning insertLast Put new character value at endempty Returns true if empty removeFirst Remove node at beginning, return value removeLast Remove node at end, return value

Page 5: Chapter 12: Lists

Programming and Problem Solving With Java 5

Writing List Classes: CharListShort 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 ! ]

Page 6: Chapter 12: Lists

Programming and Problem Solving With Java 6

Writing List Classes: CharListLonger 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); }

TextMenu CharList

CharListTest

Page 7: Chapter 12: Lists

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; }

Page 8: Chapter 12: Lists

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: 1Enter character to add to beginning: bList is now: [b ]

+--- Character List Menu ---| 1) Add first 2) Add last 3) Remove first| 4) Remove last 5) Quit| Enter selection: 1Enter character to add to beginning: aList is now: [a b ]

+--- Character List Menu ---| 1) Add first 2) Add last 3) Remove first| 4) Remove last 5) Quit| Enter selection: 2Enter character to add to end: cList is now: [a b c ]

Page 9: Chapter 12: Lists

Programming and Problem Solving With Java 9

Writing List Classes: CharListCharList is linked structure: each character on the list

keeps track of its successorCharListNode is separate class

Space for the characterReference to next character in list

Last node references null (special value)

Data value

Reference to nextnode in the list

'A'

Page 10: Chapter 12: Lists

Programming and Problem Solving With Java 10

Writing List Classes: CharListCharListNode 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;}

Data value

Reference to nextnode in the list

'A'

Page 11: Chapter 12: Lists

Programming and Problem Solving With Java 11

Writing List Classes: CharListCharList class

References first and last nodes of the list

Constructor// Default constructorpublic CharList(){ first = null; last = null; numNodes = 0;}

Referenceto first node

Numberof nodes

'A' 'B' 'C' 'D' null

4

Referenceto last node

CharList CharListNode CharListNode CharListNode CharListNode

0

null

null

Referenceto first node

Numberof nodes

Referenceto last node

CharList

Makes emptyCharList

Page 12: Chapter 12: Lists

Programming and Problem Solving With Java 12

Writing List Classes: CharListInserting 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; }}

'A' 'B' 'C' 'D' null

'E'

After creatingthe new node

4

newNode

'A' 'B' 'C' 'D' null

5

newNode 'E'

After makingthe new nodethe first node

Page 13: Chapter 12: Lists

Programming and Problem Solving With Java 13

Writing List Classes: CharListInserting a new node: insertLast()

// insertLast: Inserts a new item at the end of the listpublic 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;}

'A' 'B' 'C' 'D' null

'E'

After creatingthe new node

4

newNode null

'A' 'B' 'C' 'D'

5

newNode 'E'

After makingthe new nodethe last node

Page 14: Chapter 12: Lists

Programming and Problem Solving With Java 14

Writing List Classes: CharListRemoving a node:

removeFirst() 'A' 'B' 'C' 'D' null

node

Beforeremoving first

node

'A' 'B' 'C' 'D' null

Link aroundfirst nodenode

'C' 'D' null

Delete firstnodenode

4

4

3

'B'

Page 15: Chapter 12: Lists

Programming and Problem Solving With Java 15

Writing List Classes: CharListRemoving 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 emptypublic 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();}

Page 16: Chapter 12: Lists

Programming and Problem Solving With Java 16

Writing List Classes: CharListRemoving a node:

removeLast()

'A' 'B' 'C' 'D' null

node

Find the nodebefore the last

'A' 'B' 'C' 'D' null

Take last nodeout of list

4

3

node

null

previousNode

previousNode

'A' 'B' 'C' 'D' null

node

Beforeremoving last

node

4

Page 17: Chapter 12: Lists

Programming and Problem Solving With Java 17

Writing List Classes: CharListRemoving 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 emptypublic 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();}

Page 18: Chapter 12: Lists

Programming and Problem Solving With Java 18

Writing List Classes: CharListempty(), count(), toString()

// empty: Returns true if the list is emptypublic boolean empty(){ return first == null;}

// count: Returns the number of elements in the listpublic int count(){ return numNodes;}// toString: Returns a string representing the contents of// the listpublic String toString(){ CharListNode node = first; String result = "["; while (node != null) { result = result + node.getItem() + " "; node = node.getNext(); }

return result + "]";}

Page 19: Chapter 12: Lists

Programming and Problem Solving With Java 19

Writing List Classes: CharListProblems 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 middleCan't remove a value from the middleCan't traverse the list, except to display every elementCan't get a value from the list without removing itCan't change a value in the list without removing it and

inserting the new valueCan only store characters

Page 20: Chapter 12: Lists

Programming and Problem Solving With Java 20

A General List ClassAdditional features over CharList:

Store into the middle (not just ends)Remove from middleCheck whether a particular value is in the listGet values of elements inside the listStore any object -- not just characters

To store and retrieve elements from middle of listNeed way to refer to list positionWill add current node markerWill have methods for moving current node marker

Page 21: Chapter 12: Lists

Programming and Problem Solving With Java 21

A General List ClassList 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 thereget: Return value in current nodegoFirst: Change current node to beginninggoLast: Change current node to endgoNext: Change current node to next nodegoPrevious: Change current node to previous node insert: Put new value after current node insertFirst: Put new value at beginning

Page 22: Chapter 12: Lists

Programming and Problem Solving With Java 22

A General List ClassList operations (continued)

insertLast: Put new value at end isDefined: Return true if current node definedempty: Return true if list empty isFirst: Return true if current node is first node isLast: Return true if current node is last nodeput: 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

Page 23: Chapter 12: Lists

Programming and Problem Solving With Java 23

A General List Class: Line EditorToday, most editors are full-screen

Move cursor with keys or mouseType at position of cursor

Older style: line editorMake changes to one line at a timeMust specify line to change with a commandNot as easy to use as full-screen editorMuch easier to write, though

Page 24: Chapter 12: Lists

Programming and Problem Solving With Java 24

A General List Class: Line EditorExample of line editor: MS-DOS edlin

C:\>edlin Hello.javaNew 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: }*EC:\>

Linecommands Current line

(markedwith *)

Page 25: Chapter 12: Lists

Programming and Problem Solving With Java 25

A General List Class: Line EditorWill use List class to make line editor

Store each line in a list nodeCommands

Show all lines with line numbers Insert lines after a given line numberDelete a lineQuit the program

To insert linesType as many lines as desiredType just period on line to end

Page 26: Chapter 12: Lists

Programming and Problem Solving With Java 26

A General List Class: Line EditorExample 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: s1: This is the first line in the editor. The2: editor is in insert mode. When a period is3: typed by itself, insert mode stops.

+--- Edit Menu ---| s) Show all lines i) Insert lines d) Delete a line| q) Quit| Enter selection: iAfter which line: 2(Enter just a period to stop inserting lines): --- This is the new third line. ---: .

Page 27: Chapter 12: Lists

Programming and Problem Solving With Java 27

A General List Class: Line EditorExample run of line editor (continued)

+--- Edit Menu ---| s) Show all lines i) Insert lines d) Delete a line| q) Quit| Enter selection: s1: This is the first line in the editor. The2: editor is in insert mode. When a period is3: --- 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: dLine to delete: 3

+--- Edit Menu ---| s) Show all lines i) Insert lines d) Delete a line| q) Quit| Enter selection: s1: This is the first line in the editor. The2: editor is in insert mode. When a period is3: typed by itself, insert mode stops.

+--- Edit Menu ---| s) Show all lines i) Insert lines d) Delete a line| q) Quit| Enter selection: qAre you sure you want to quit? (y/n): y

Page 28: Chapter 12: Lists

Programming and Problem Solving With Java 28

A General List Class: Line EditorDesign of the line editor program

Will use the TextMenu framework for menusWill use the List class to store lines

TextMenu

EditApplication

List

Page 29: Chapter 12: Lists

Programming and Problem Solving With Java 29

A General List Class: Line EditorMethods in EditApplication class

EditApplication(): Constructor, initializes menuhandleEvent(): Event dispatchergoToLine(): 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

Page 30: Chapter 12: Lists

Programming and Problem Solving With Java 30

A General List Class: Line EditorEditApplication constructor

// Constructor - set up menu for the editorpublic 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 constantsstatic 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();}

Page 31: Chapter 12: Lists

Programming and Problem Solving With Java 31

A General List Class: Line EditorEditApplication handleEvent()

// Event dispatcher for the editorpublic 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;}

Page 32: Chapter 12: Lists

Programming and Problem Solving With Java 32

A General List Class: Line EditorEditApplication 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.

Page 33: Chapter 12: Lists

Programming and Problem Solving With Java 33

A General List Class: Line EditorEditApplication 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(": "); }}

Page 34: Chapter 12: Lists

Programming and Problem Solving With Java 34

A General List Class: Line EditorEditApplication gotoLine()

// goToLine: Changes the current line to a specific line number// Note: lineNum must be in the range 1 to number of lines// in buffervoid 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(); }}

Page 35: Chapter 12: Lists

Programming and Problem Solving With Java 35

A General List Class: Line EditorEditApplication deleteLine() steps

Ask the user which line to deleteMove to that lineDelete that line

EditApplication deleteLine()// deleteLine: Prompts user for a line number, then deletes// that linevoid 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(); }}

Page 36: Chapter 12: Lists

Programming and Problem Solving With Java 36

A General List Class: Line EditorEditApplication displayLines()

// displayLines: Display all lines in the buffervoid 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 listMove to first line with goFirst()Test whether past end of list with isDefined()Move to next line with goNext()

Page 37: Chapter 12: Lists

Programming and Problem Solving With Java 37

A General List Class: ImplementationList is a container type

Holds elements of another typeArray is another container typeCommon implementation of a container as a linked

typeClass for each node of the containerClass for the container itself

Used this implementation with CharListCharListNodeCharList

Will store an Object value in each node

Page 38: Chapter 12: Lists

Programming and Problem Solving With Java 38

A General List Class: ImplementationListNode 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;}

Page 39: Chapter 12: Lists

Programming and Problem Solving With Java 39

A General List Class: ImplementationList class structure

Instance variables// Instance variablesint numNodes; // The number of nodes in the listListNode first, // Reference to the first node last, // Reference to the last node currentNode; // Reference to the current node

Reference tofirst node

Numberof nodes

1 2 3 4 null

4

Reference tolast node

List ListNode ListNode ListNode ListNode

Reference tocurrent node

Page 40: Chapter 12: Lists

Programming and Problem Solving With Java 40

A General List Class: ImplementationList constructor

// Default constructorpublic 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; }}

Page 41: Chapter 12: Lists

Programming and Problem Solving With Java 41

A General List Class: ImplementationList insertLast (similar to CharList)

// insertLast: Inserts a new item at the end of the listpublic 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;}

Page 42: Chapter 12: Lists

Programming and Problem Solving With Java 42

A General List Class: ImplementationList insert()

Puts new node after currentNodeCaller responsible for setting currentNode first

// insert: Inserts a new item after a node pointed to by// currentNode.// Note: currentNode must be definedpublic 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; }}

Page 43: Chapter 12: Lists

Programming and Problem Solving With Java 43

A General List Class: ImplementationList put()

// put: Changes the value of the currentNode node to item// Note: currentNode must be definedpublic 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 definedpublic Object get(){ Debug.assert(isDefined(), "List.get(): currentNode undefined"); return currentNode.getItem();}

Page 44: Chapter 12: Lists

Programming and Problem Solving With Java 44

A General List Class: ImplementationList 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 emptypublic Object removeFirst(){ Debug.assert(!empty(), "List.removeFirst(): List is empty");

Object returnValue = first.getItem(); removeNode(first, null); return returnValue;}

Page 45: Chapter 12: Lists

Programming and Problem Solving With Java 45

A General List Class: ImplementationList 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 emptypublic 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;}

Page 46: Chapter 12: Lists

Programming and Problem Solving With Java 46

A General List Class: ImplementationList 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 definedpublic 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 onepublic void append(List source){ for (source.goFirst(); source.isDefined(); source.goNext()) { insertLast(source.get()); }}

Page 47: Chapter 12: Lists

Programming and Problem Solving With Java 47

A General List Class: ImplementationList 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;}

Page 48: Chapter 12: Lists

Programming and Problem Solving With Java 48

A General List Class: ImplementationList goFirst()

// goFirst: Sets currentNode to beginning of listpublic void goFirst(){ currentNode = first;}

List goList()// goLast: Sets currentNode to end of listpublic void goLast(){ currentNode = last;}

List goNext()// goNext: Sets currentNode to next element in the list// Note: currentNode must be definedpublic void goNext(){ Debug.assert(isDefined(), "List.goNext(): currentNode undefined"); currentNode = currentNode.getNext();}

Page 49: Chapter 12: Lists

Programming and Problem Solving With Java 49

A General List Class: ImplementationList goPrevious()

// goPrevious: Sets currentNode to previous element in// the list// Note: currentNode must be definedpublic void goPrevious(){ Debug.assert(isDefined(), "List.goPrevious(): currentNode undefined"); currentNode = findPreviousNode(currentNode);}

Page 50: Chapter 12: Lists

Programming and Problem Solving With Java 50

A General List Class: ImplementationRemoving a node

1 2 3 4 null

node

BeforeremovingpreviousNode

1 2 3 4 null

node

Link aroundnodepreviousNode

4

3

Page 51: Chapter 12: Lists

Programming and Problem Solving With Java 51

A General List Class: ImplementationList removeNode()

// removeNode: Removes the given node from the list, adjusts// first, last, and currentNode// if necessary. If node is currentNode,// then sets currentNode to next node, // unless deleting the last node. In that// case, sets currentNode to previous node.void removeNode(ListNode node, ListNode previousNode){ if (node == first) { first = first.getNext(); } else { previousNode.setNext(node.getNext()); }

if (last == node) { last = previousNode; }

// Reset currentNode, if necessary if (currentNode == node) { if (currentNode.next == null) { currentNode = previousNode; } else { currentNode = currentNode.getNext(); } }

numNodes--;}

Page 52: Chapter 12: Lists

Programming and Problem Solving With Java 52

A General List Class: ImplementationList findPreviousNode()

Modified linear searchMust find the node before the one we want

// findPreviousNode: Returns the node before the given// node, or null if the node is the// first node in the list.// Pre: node must be a valid node in the listListNode findPreviousNode(ListNode node){ ListNode previousNode;

if (node == first) { return null; }

previousNode = first; while (previousNode.getNext() != node) { previousNode = previousNode.getNext(); } return previousNode;}

Page 53: Chapter 12: Lists

Programming and Problem Solving With Java 53

Infinite Precision ArithmeticRange of long may not be enough

-9,223,372,036,854,775,808 9,223,372,036,854,775,807Can make a type that holds any number of digits

// Sample use of the InfinitePrecision class.

import InfinitePrecision;

public class TestInfinitePrecision{ public static void main(String[] args) { InfinitePrecision first = new InfinitePrecision( "4958614030582059703402389481948372634758695783"); InfinitePrecision second = new InfinitePrecision( "8089614672364869790583723648597007904201129034");

System.out.println("The sum of: " + first); System.out.println(" and: " + second); System.out.println(" is: " + first.add(second)); }}

The sum of: 4958614030582059703402389481948372634758695783 and: 8089614672364869790583723648597007904201129034 is: 13048228702946929493986113130545380538959824817

Page 54: Chapter 12: Lists

Programming and Problem Solving With Java 54

Infinite Precision ArithmeticInfinitePrecision instance variable

// Instance variablesList digits = new List();

InfinitePrecision default constructorUse this when we want to assign 0 to the number

// Default Constructor// Note: An empty list is treated as zeropublic InfinitePrecision(){}

Page 55: Chapter 12: Lists

Programming and Problem Solving With Java 55

Infinite Precision ArithmeticInfinitePrecision constructor with long argument

// Constructor: Sets the number to that given in the// long integerpublic InfinitePrecision(long number){ // Put digits in number from right to left while (number != 0) { digits.insertFirst(new Integer((int) (number % 10))); number = number / 10; }}

Trace on new InfnitePrecision(12345);step number digits (list)

0 12345 []

1 1234 [5]

2 123 [4, 5]

3 12 [3, 4, 5]

4 1 [2, 3, 4, 5]

5 0 [1, 2, 3, 4, 5]

Page 56: Chapter 12: Lists

Programming and Problem Solving With Java 56

Infinite Precision ArithmeticInfinitePrecision constructor with string argument

// Constructor: Sets the number to that given in the string// Note: The string should have only digitspublic InfinitePrecision(String number){ int i = 0;

while (i < number.length()) { Debug.assert(Character.isDigit(number.charAt(i)), "InfinitePrecision(): invalid character in string"); digits.insertLast( new Integer(Character.digit(number.charAt(i), 10))); i++; }}

Trace on new InfnitePrecision(“12345”); i number digits (list)

0 "12345" []

1 "12345" [1]

2 "12345" [1, 2]

3 "12345" [1, 2, 3]

4 "12345" [1, 2, 3, 4]

5 "12345" [1, 2, 3, 4, 5]

Page 57: Chapter 12: Lists

Programming and Problem Solving With Java 57

Infinite Precision ArithmeticAdding two infinite precision numbers

Use the manual technique from right to left

2 6 4 27 8 5

3 4 2 7

+

11

Carry

Page 58: Chapter 12: Lists

Programming and Problem Solving With Java 58

Infinite Precision ArithmeticInfinitePrecision add() (part1)

// add: Returns sum of this value and the other// InfinitePrecision valueInfinitePrecision add(InfinitePrecision otherValue){ InfinitePrecision result = new InfinitePrecision(); int carry = 0;

digits.goLast(); otherValue.digits.goLast();

// Add digits from right to left while (digits.isDefined() && otherValue.digits.isDefined()) { result.digits.insertFirst(new Integer( (((Integer) digits.get()).intValue() + ((Integer) otherValue.digits.get()).intValue() + carry) % 10)); carry = (((Integer) digits.get()).intValue() + ((Integer) otherValue.digits.get()).intValue() + carry) / 10; digits.goPrevious(); otherValue.digits.goPrevious(); }

Page 59: Chapter 12: Lists

Programming and Problem Solving With Java 59

Infinite Precision ArithmeticInfinitePrecision add() (part2)

// Append any remaining digits from this value to result's // left for (; digits.isDefined(); digits.goPrevious()) { result.digits.insertFirst(new Integer( (((Integer) digits.get()).intValue() + carry) % 10)); carry = (((Integer) digits.get()).intValue() + carry) / 10; }

// Append any remaining digits from other value to result's // left for (; otherValue.digits.isDefined(); otherValue.digits.goPrevious()) { result.digits.insertFirst(new Integer( (((Integer) otherValue.digits.get()).intValue() + carry) % 10)); carry = (((Integer) otherValue.digits.get()).intValue() + carry) / 10; }

if (carry != 0) { result.digits.insertFirst(new Integer(carry)); }

return result;}

Page 60: Chapter 12: Lists

Programming and Problem Solving With Java 60

Infinite Precision ArithmeticInfinitePrecision toString()

// toString: Returns a String version of the number public String toString() { String result = ""; if (digits.empty()) { return "0"; } else { for (digits.goFirst(); digits.isDefined(); digits.goNext()) { result = result + digits.get(); } return result; } }

Page 61: Chapter 12: Lists

Programming and Problem Solving With Java 61

Making List work with PrimitivesCan store objects in a List directly

List myList = new List();

myList.insertFirst(“a string”);

Must wrap primitivesmyList.insertFirst(new Integer(1234));myList.insertLast(new Double(6.39));

Can overload List methods so they work with primitives

// insertFirst: Inserts a new int at the beginning of the// list (Overloaded version for int)public void insertFirst(int item){ insertFirst(new Integer(item));}

Now can store integers directlymyList.insertFirst(1234);

Should also overload for other primitives (long, float, ...)

Page 62: Chapter 12: Lists

Programming and Problem Solving With Java 62

Making List work with PrimitivesMust cast values from a list, and unwrap primitives

String aString = (String) myList.get();int anInt = ((Integer) myList.get()).intValue();

Unfortunately, can’t override get() to return intOverriding works only when parameters differ

To retrieve primitives from List easilyWrite getInt() for retrieving integers, getDouble() for

doubles, etc.// getInt: Returns the int value in the currentNode// (Overloaded version for int)// Note: currentNode must be definedpublic int getInt(){ return ((Integer) get()).intValue();}

This is why Keyboard class has readInt(), readString(), ...Use of getInt() is more readable than get()

int anInt = myList.getInt();

Page 63: Chapter 12: Lists

Programming and Problem Solving With Java 63

Sorting a ListTwo ways to sort a list

Keep it sorted all the timeUsers can’t put elements where they want

Sort only when neededMore flesxibleUsers can put elements anywhere - can sort later if ncessary

ProblemList stores Object valuesObjects have no order -- how to sort them??Specific objects (dates, strings, ...) do have an order,

thoughCan’t put sort() in List class

Page 64: Chapter 12: Lists

Programming and Problem Solving With Java 64

Sorting a List: ComparatorsCan make a subclass of List that allows sortingPut responsibility for sorting in separate classWrite a Comparator class

Comparator: object that compares two other objectsTells which object is less

Comparator compares Object valuesComparator is an abstract classWhy? Can’t compare Object valuesUse as a template for subclasses of Comparator

Page 65: Chapter 12: Lists

Programming and Problem Solving With Java 65

Sorting a List: ComparatorsComparator class

public abstract class Comparator{ // compareTo: returns negative number if a < b // 0 if a == b // positive number if a > b abstract public int compareTo(Object a, Object b);}

Subclass of Comparator for comparing stringspublic class StringComparator extends Comparator{ // compareTo: returns negative number if a < b // 0 if a == b // positive number if a > b public int compareTo(Object a, Object b) { return ((String) a).compareTo((String) b); }}

Page 66: Chapter 12: Lists

Programming and Problem Solving With Java 66

Sorting a List: ComparatorsSubclass of Comparator for comparing integers

public class IntegerComparator extends Comparator{ // compareTo: returns negative number if a < b // 0 if a == b // positive number if a > b public int compareTo(Object a, Object b) { int inta = ((Integer) a).intValue(); int intb = ((Integer) b).intValue();

if (inta < intb) { return -1; } if (inta > intb) { return 1; } return 0; }}

Page 67: Chapter 12: Lists

Programming and Problem Solving With Java 67

Sorting a List: SortableListSkeleton for SortableList class

import List;import Comparator;

public class SortableList extends List{ // Constructor public SortableList(Comparator comparator) { this.comparator = comparator; }

// --------------------------------------------------------------- // Sort method can go here. It should use comparator.compareTo() // to compare elements of the list. // ---------------------------------------------------------------

// Instance variables Comparator comparator;}

Inherits all the methods of List: insert(), remove(), ...Can use any sorting algorithm in SortableList

Page 68: Chapter 12: Lists

Programming and Problem Solving With Java 68

Sorting a List: Quick SortQuick sort

Very fast and efficientOn average, the fastest known sorting algorithmCan be very slow occasionallyWorks well with lists (and arrays)

Page 69: Chapter 12: Lists

Programming and Problem Solving With Java 69

Quick SortHow quick sort works

Choose pivot Make list of elements

less than pivot Make list of elements

greater than pivot Sort both lists

(using quick sort) Combine the sorted

lists

{4, 2, 6, 1, 3, 7, 5}

4

Step 1: Choose apivot element

[4, 2, 6, 1, 3, 7, 5]

[2, 3, 1] 4

Step 2: Make a listof elements less

than the pivot

[4, 2, 6, 1, 3, 7, 5]

[6, 7, 5][2, 3, 1] 4

Step 3: Make a listof elements more

than the pivot

[5, 6, 7][1, 2, 3] 4

Step 4: Sort sublistsand append

[1, 2, 3, 4, 5, 6, 7]

Pivot

PivotLessthanpivot

PivotLessthanpivot

Greaterthanpivot

PivotLessthanpivot

Greaterthanpivot

Page 70: Chapter 12: Lists

Programming and Problem Solving With Java 70

Quick SortChoice of pivot is critical in quick sort

Ideally, the pivot should be the middle value of the list If list is already sorted, choosing first element gives very

slow sort (why?)Common pivot selection technique for array

Choose middle value of:array[0]array[array.length-1]array[array.length / 2]

Even better: choose random element as the pivotCan’t get middle element from list (efficiently)

Ideas for choosing apivot value for a list??

Page 71: Chapter 12: Lists

Programming and Problem Solving With Java 71

SortableList quickSort() // quickSort: Sorts the list public void quickSort() { SortableList lessList = new SortableList(comparator); SortableList greaterList = new SortableList(comparator); Object pivot, element;

goFirst(); if (!isEmpty()) { pivot = removeFirst(); while (!isEmpty()) { element = removeFirst(); if (comparator.compareTo(element, pivot) < 0) { lessList.insertFirst(element); } else { greaterList.insertFirst(element); } } lessList.quickSort(); greaterList.quickSort();

// Append lists to get result append(lessList); insertLast(pivot); append(greaterList); } }

Page 72: Chapter 12: Lists

Programming and Problem Solving With Java 72

SortableList quickSort()Demonstration of SortableList

// Demonstrates the use of the SortableList class,// which contains a quick sort algorithm.

import SortableList;import StringComparator;

public class TestSortableList{ public static void main(String[] args) { SortableList myList = new SortableList(new StringComparator());

myList.insertFirst("banana"); myList.insertFirst("orange"); myList.insertFirst("apple"); myList.insertFirst("grape"); myList.insertFirst("pear"); myList.insertFirst("strawberry"); myList.insertFirst("cherry");

System.out.println("Before sort: " + myList); myList.quickSort(); System.out.println("After sort: " + myList); }}Before sort: [cherry strawberry pear grape apple orange banana ]

After sort: [apple banana cherry grape orange pear strawberry ]

Page 73: Chapter 12: Lists

Programming and Problem Solving With Java 73

SortableList quickSort()Another Demonstration of SortableList

// Demonstrates the use of the SortableList class,// which contains a quick sort algorithm.

import SortableList;import IntegerComparator;

public class TestSortableList2{ public static void main(String[] args) { SortableList myList = new SortableList(new IntegerComparator());

myList.insertFirst(3); // Note use of special insertFirst() myList.insertFirst(8); // made especially for int type myList.insertFirst(2); // (Otherwise, would need to use myList.insertFirst(1); // new Integer(3), for example, myList.insertFirst(4); // instead of 3) myList.insertFirst(7); myList.insertFirst(5);

System.out.println("Before sort: " + myList); myList.quickSort(); System.out.println("After sort: " + myList); }} Before sort: [5 7 4 1 2 8 3 ]

After sort: [1 2 3 4 5 7 8 ]

Page 74: Chapter 12: Lists

Programming and Problem Solving With Java 74

A Set TypeSet: heterogeneous, unordered collection of

elements without duplicate valuesCommon set operations

O p e r a t i o n S y m b o l D e s c r i p t i o n E x a m p l e

U n i o n T h e u n i o n o f t w o s e t s i se v e r y t h i n g t h a t i s i ne i t h e r s e t .

{ , } { , } { , , }1 2 2 3 1 2 3

I n t e r s e c t i o n T h e i n t e r s e c t i o n o f t w os e t s i s e v e r y t h i n g t h a t i si n b o t h s e t s .

{ , } { , } { }1 2 2 3 2

D i f f e r e n c e T h e d i f f e r e n c e o f t w os e t s i s e v e r y t h i n g t h a t i st h e f i r s t s e t b u t n o t i n t h es e c o n d .

{ , } { , } { }1 2 2 3 1

Page 75: Chapter 12: Lists

Programming and Problem Solving With Java 75

A Set TypeSet operations

Union

Intersection Difference

A B

A B A B

Page 76: Chapter 12: Lists

Programming and Problem Solving With Java 76

A Set TypeDemonstration of how to use the Set class

// Demonstrates use of the Set class

import Set;

public class TestSet{ public static void main(String[] args) { // Make two sets Set a = new Set(); Set b = new Set();

// Put 1 and 2 in set a a.add("1"); a.add("2");

// Put 2 and 3 in set b b.add("2"); b.add("3");

// Display results System.out.println("Set a is " + a); System.out.println("Set b is " + b); System.out.println("a union b is " + a.union(b)); System.out.println("a intersect b is " + a.intersect(b)); System.out.println("a difference b is " + a.difference(b)); }}

Set a is {2 1}Set b is {3 2}a union b is {1 3 2}a intersect b is {2}a difference b is {1}

Page 77: Chapter 12: Lists

Programming and Problem Solving With Java 77

A Set Type: ImplementationStore set elements in a list

// Instance variablesList data = new List();

Constructor for Set// Default constructorpublic Set(){}

add() method must not insert duplicate values// add: Adds an element to a set if not already in the set.// If the element is already in the set, it is not// added again.public void add(Object item){ if (!isMember(item)) { data.insertFirst(item); }}

Page 78: Chapter 12: Lists

Programming and Problem Solving With Java 78

A Set Type: ImplementationSet remove() method

// remove: Removes the given item from the set. Does nothing// if the element is not in the set.public void remove(Object item){ if (data.find(item)) { data.remove(); }}

Easy to writeList class methods do all the work

Page 79: Chapter 12: Lists

Programming and Problem Solving With Java 79

A Set Type: ImplementationSet union() method

// union: Returns the union of this set and otherSet, that// is, all items in either set.public Set union(Set otherSet){ Set result = new Set();

// Copy everything from otherSet to result result.data.append(otherSet.data);

// Add items from this set to the result (The add() member // method will make sure that no element is added twice.) for (data.goFirst(); data.isDefined(); data.goNext()) { result.add(data.get()); } return result;}

Another approach: use add() for both setsNot as efficient - don’t need to check for duplicates until

second set added

Page 80: Chapter 12: Lists

Programming and Problem Solving With Java 80

A Set Type: ImplementationSet intersect() method

// intersect: Returns the intersection of this set and// otherSet, that is, all items in both sets.public Set intersect(Set otherSet){ Set result = new Set();

// Copy items from this set that are also in otherSet to // result for (data.goFirst(); data.isDefined(); data.goNext()) { if (otherSet.isMember(data.get())) { result.add(data.get()); } } return result;}

Page 81: Chapter 12: Lists

Programming and Problem Solving With Java 81

A Set Type: ImplementationSet difference() method

// difference: Returns the difference of this set and// otherSet, that is, all items in this set but// not in otherSet.public Set difference(Set otherSet){ Set result = new Set();

// Copy those items from this set that are not in otherSet // to result for (data.goFirst(); data.isDefined(); data.goNext()) { if (!otherSet.isMember(data.get())) { result.add(data.get()); } } return result;}

Page 82: Chapter 12: Lists

Programming and Problem Solving With Java 82

A Set Type: ImplementationSet toString() method

// toString: Returns the set's contents as a string in// standard displayable format: {1, 3, 2}public String toString(){ String listStr = data.toString(); return "{" + listStr.substring(1, listStr.length() - 2) + "}";}

Page 83: Chapter 12: Lists

Programming and Problem Solving With Java 83

A Set Type: ImplementationSet count(), empty(), isFull(), isMember() methods

// count: Returns the number of items in the setpublic int count(){ return data.count();}

// empty: Returns true if the set is empty, false// otherwisepublic boolean empty(){ return data.empty();}

// isFull: Returns true if the set is not empty, false// otherwise (always return false for list// implemention)public boolean isFull(){ return false;}

// isMember: Returns true if item is in the set, false// otherwiseboolean isMember(Object item){ return data.find(item);}

Page 84: Chapter 12: Lists

Programming and Problem Solving With Java 84

Doubly Linked ListsSingly linked list

Each node references its successorCan only move from node to next node

Doubly linked listEach node references successor and predecessorAdvantage: Can delete node without searching for

successor and predecessorAdvantage: Can go through list backward

Reference tofirst node

Numberof nodes

2 3 null

3

Reference tolast node

DList DListNode

1null

DListNode DListNode

Reference tocurrent node

Page 85: Chapter 12: Lists

Programming and Problem Solving With Java 85

Doubly Linked ListsProblems with doubly linked lists

Takes more memory than singly linkedLots of special cases in implementation

Can remove many special cases withDummy header: unused nodeCircular references

1 2

HeaderReferenceto header

node

Number ofnodes

2

DList

Referenceto current

node

Page 86: Chapter 12: Lists

Programming and Problem Solving With Java 86

Doubly Linked ListsEmpty doubly linked list

Note: reference to end of list not necessary

HeaderReferenceto header

node

Number ofnodes

0

DList

NULLReferenceto current

node

Page 87: Chapter 12: Lists

Programming and Problem Solving With Java 87

Doubly Linked List: ImplementationDoubleListNode class

class DoubleListNode{ // Default Constructor public DoubleListNode() { this(null, null, null); // (This is the default action, but it // doesn't hurt to be explicit) }

// Constructor public DoubleListNode(Object item, DoubleListNode previous, DoubleListNode next) { this.item = item; this.previous = previous; this.next = next; } // getItem: Returns the item value public Object getItem() { return item; }

// getNext: Returns the next item public DoubleListNode getNext() { return next; }

Page 88: Chapter 12: Lists

Programming and Problem Solving With Java 88

Doubly Linked List: ImplementationDoubleListNode class (continued)

// getPrevious: Returns the previous item public DoubleListNode getPrevious() { return previous; }

// 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(DoubleListNode next) { this.next = next; }

// setPrevious: Sets the previous item to the given object public void setPrevious(DoubleListNode previous) { this.previous = previous; }

// Instance variables DoubleListNode next, previous; Object item;}

Page 89: Chapter 12: Lists

Programming and Problem Solving With Java 89

Doubly Linked List: ImplementationDoubleList instance variables

// Instance variablesDoubleListNode header; // Reference to dummy headerDoubleListNode currentNode; // Reference to current nodeint numNodes; // Number of nodes in list

DoubleList constructor// Default constructorpublic DoubleList(){ numNodes = 0; // Allocate dummy header node header = new DoubleListNode(); header.setPrevious(header); header.setNext(header);}

HeaderReferenceto header

node

Number ofnodes

0

DList

NULLReferenceto current

node

Page 90: Chapter 12: Lists

Programming and Problem Solving With Java 90

Doubly Linked List: ImplementationInserting a

node atthebeginningof a list

1 2

HeaderDList

3

temp

1 2

HeaderDList

3

temp

After creatingthe new node

After insertingthe new node

Referenceto header

node

Number ofnodes

2

Referenceto current

node

Referenceto header

node

Number ofnodes

3

Referenceto current

node

Page 91: Chapter 12: Lists

Programming and Problem Solving With Java 91

Doubly Linked List: ImplementationDoubleList insert() method

// insertFirst: Inserts a new item at the beginning of the// listpublic void insertFirst(Object item){ DoubleListNode oldFirstNode = header.getNext(); DoubleListNode newNode = new DoubleListNode(item, header, oldFirstNode);

numNodes++; oldFirstNode.setPrevious(newNode); header.setNext(newNode);}

Page 92: Chapter 12: Lists

Programming and Problem Solving With Java 92

Doubly Linked List: ImplementationRemoving

a value from alist

1 2

Header

Beforeremoving

1 2

Header

Link aroundnode

2

Header

Adjust currentnode

DListReferenceto header

node

Number ofnodes

2

Referenceto current

node

DListReferenceto header

node

Number ofnodes

2

Referenceto current

node

DListReferenceto header

node

Number ofnodes

1

Referenceto current

node

Page 93: Chapter 12: Lists

Programming and Problem Solving With Java 93

Doubly Linked List: ImplementationDoubleList 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 definedpublic Object remove(){ Debug.assert(isDefined(), "DoubleList.remove(): currentNode undefined"); Object returnValue = currentNode.getItem(); removeNode(currentNode); return returnValue;}

Page 94: Chapter 12: Lists

Programming and Problem Solving With Java 94

Doubly Linked List: ImplementationDoubleList removeNode()

// removeNode: Removes the given node from the list, adjusts// first, last, and currentNode// if necessary. If node is currentNode,// then sets currentNode to next node, // unless deleting the last node. In that// case, sets currentNode to previous node.void removeNode(DoubleListNode node){ DoubleListNode nextNode = node.getNext(), previousNode = node.getPrevious();

previousNode.setNext(nextNode); nextNode.setPrevious(previousNode); numNodes--;

// Reset currentNode, if necessary if (currentNode == node) { if (currentNode.next == header) { currentNode = previousNode; } else { currentNode = nextNode; } }}

Page 95: Chapter 12: Lists

Programming and Problem Solving With Java 95

Doubly Linked List: ImplementationDoubleList 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){ DoubleListNode node = header.getNext();

// Find node containing the data value while (node != header && !(node.getItem().equals(data))) { node = node.getNext(); }

if (node == header) { return false; } currentNode = node; return true;}

Page 96: Chapter 12: Lists

Programming and Problem Solving With Java 96

Computer Security: LayersLayers of security

Personnel screening

Intrusion prevention

Intrusion detection

Operating system authentication

Database authentication

Inference and access controls

Encryption

Protected Information

ATTACK

Page 97: Chapter 12: Lists

Programming and Problem Solving With Java 97

Computer Security: LayersPhysical security: intrusion prevention and detection

FencesLack of windowsWalls that extend to the roofMechanical and electronic locksGuardsAdequate lightingAutomated entry boothsUninterruptible power suppliesPower filters and surge suppressorsSmoke and fire detectionAutomatic fire extinguishers

Page 98: Chapter 12: Lists

Programming and Problem Solving With Java 98

Computer Security: LayersOperating system

Identification: unique name for each userAuthentication: confirmation of user by computer and vice

versaAuthentication techniques

Check what user knows (password, ...)Check what user carries (smartcard, ...)Check who user is (retina scan, voice print, ...)

Password recommendations (US DoD)Users should be able to changeShould be machine generatedSystem should display last login time

Page 99: Chapter 12: Lists

Programming and Problem Solving With Java 99

Computer Security: DisclosureDisclosure of information can be harmful

Military and government disclosure: national securityCommercial disclosure: trade secrets, customer lists, ...

US Laws forbidding disclosure of personal informationRight to Financial Privacy (1978)Privacy Act (1974) (Other countries have similar laws)

Page 100: Chapter 12: Lists

Programming and Problem Solving With Java 100

Computer Security: DisclosureCovert channel

Unconventional method of information transfer

Types of covert channels Storage Timing

Very difficult to identify covert channels

Message

Message not allowed

Disk Drive

Movediskhead

Detecthead

movement

User A User B

Page 101: Chapter 12: Lists

Programming and Problem Solving With Java 101

Computer Security: DisclosureIndirect disclosure: inference or aggregationInference

Can guess value by adding outside informationExample: Anderson is only female managerCan guess Anderson’s salary from FSalary - TSalary

•FSalary, total salary of all females•TSalary, total salary of all non-manager females

AggregationCan guess value by combining nonsensitive valuesExample: knowing 1 CIA phone number is OkKnowing ALL CIA phone numbers is NOT Ok

Page 102: Chapter 12: Lists

Programming and Problem Solving With Java 102

Computer Security: ModificationData modification or destruction more serious to

commercial computersUsually caused by disgruntled employees

Trapdoor: turns off normal security checkingExample: no password for some accounts

Trojan horse: malicious program hidden in anotherVirus: self-perpetuating Trojan horse, attaches to

other programsWorm: self-perpetuating program takes over idle

machines in a networkTime bombs and logic bombs

Page 103: Chapter 12: Lists

Programming and Problem Solving With Java 103

Computer Security: MilitaryFocus: control of disclosureSensitivity levels

UnclassifiedConfidentialSecretTop secret

Compartments: topic areasNuclearSpy ...

Each object has security levelEach user has clearance

NUCSPY

Top Secret

Secret

Confidential

Unclassified

o3

o1

o2

Page 104: Chapter 12: Lists

Programming and Problem Solving With Java 104

Computer Security: MilitaryMandatory access control (MAC)

Enforcement of military securityUnauthorized disclosure is illegal

Discretionary access control (DAC)Owner of data decides who can access itMost common commercial security techniqueUsed in many operating systems (NT, Unix, VAX VMS)

MAC and DAC combined = military security

Page 105: Chapter 12: Lists

Programming and Problem Solving With Java 105

Computer Security: MilitaryModes of operation for military computers

Dedicated: users cleared for all data, can access all dataSystem-high: users cleared for all data, can access some

dataCompartmented: users cleared for most restricted data,

can access some dataMultilevel: users not cleared for all data, can access

some dataMost military computers run in system-high modeMilitary would like to move to multilevel

CheaperEasier to keep data consistent

Page 106: Chapter 12: Lists

Programming and Problem Solving With Java 106

Computer Security: MilitaryDoD security classificationsLevel D

No securityLevel C (C1, C2)

Discretionary access controlNT, VAX VMS, some variants of Unix are C2C2 is minimum for commercial security

Level B (B1, B2, B3)Level C featuresPlus mandatory access control

Level ALevel B featuresPlus formal proof of correctness

Page 107: Chapter 12: Lists

Programming and Problem Solving With Java 107

Computer Security: Access ControlDiscretionary access control (DAC)

Allows data owner to choose who else can accessLittle protection against Trojan horse attacks

Implementation of DACCapabilitiesAccess control listsProtection bits

CapabilitiesSystem associates access rights

with each userAdvantage: more protection

against Trojan horse attacksDisadvantage: revoking rights

is difficult

User A

Files RightsFILE1 R, WFILE2 R

User BFiles RightsFILE1 RFILE2 R, WFILE3 R, W

User C

Files RightsFILE2 RFILE3 R, W

Page 108: Chapter 12: Lists

Programming and Problem Solving With Java 108

Computer Security: Access ControlAccess control lists

Another way to implement DACStores list of authorized users

with each resourceUS National Computer

Center recommends thisapproach

Users RightsUser A R, WUser B R

FILE1

FILE2

FILE3

Users RightsUser A RUser B R, WUser C R

Users RightsUser B R, WUser C R, W

Page 109: Chapter 12: Lists

Programming and Problem Solving With Java 109

Computer Security: Access ControlProtection bits

Another way to implement DAC9 bits (Boolean values) per object

Owner read Group read Others readOwner write Group write Others writeOwner execute Group execute Others execute

Used with many Unix variants% ls -l newmodel.txt-rw-rw---- 1 slack 219 Jan 6 14:07 newmodel.txt

Change projection with chmod% chmod u-w newmodel.txt-r--rw---- 1 slack 219 Jan 6 14:07 newmodel.txt

Simplest approach to implement DACBut weak protection -- doesn’t qualify for level C security

Page 110: Chapter 12: Lists

Programming and Problem Solving With Java 110

Computer Security: CommercialCommercial security emphasizes prevention of

unauthorized modificationMost common unauthorized modification

Page 111: Chapter 12: Lists

Programming and Problem Solving With Java 111

Computer Security: CommercialMajor types of undesirable changes

Unauthorized user inserts false information deliberatelyAuthorized user inserts false information accidentally

Prevent unauthorized changes with security techniquesMACDAC

How to prevent accidental changes?

Page 112: Chapter 12: Lists

Programming and Problem Solving With Java 112

Computer Security: CommercialCan’t prevent all accidental changesPrevent most of them with integrity constraints

(business rules)Age of employees must be between 18 and 80No employee can earn more than his or her manager

IntegrityValidity (no false information)Completeness (all true information included)

Integrity usually enforced at database levelCorrect state: when data satisfies all Integrity constraints

Database system tries to keep data in correct state

Page 113: Chapter 12: Lists

Programming and Problem Solving With Java 113

Computer Security: CommercialTransaction: group of changes to data

Must take database from one correct state to another correct state

Transaction example Integrity constraint: Sales + value of inventory is constantCustomer buys shoes: steps in database

1. Subtract value of shoes from inventory2. Add amount of sale to sum of today’s sales

Incorrect state between stepsCorrect state only after both steps completed

Page 114: Chapter 12: Lists

Programming and Problem Solving With Java 114

Computer Security: CommercialTypes of database integrity constraints

Structure-based: part of the database structureValue-based: based on values in the database

Structure-based exampleCan only store an integer in an Age field (defined as

Integer)Value-based example

No employee can earn more than his or her manager

Page 115: Chapter 12: Lists

Programming and Problem Solving With Java 115

Computer Security: CommercialClark-Wilson model of integrity

Only transaction procedures can change dataUsers can only use transaction

procedures -- can’t access data directlyTask: several transactionsSeparation of duties: make sure a different person

handles each transaction in a taskExample: Paying a supplier

Receive new inventoryApprove supplier’s invoiceRequest payment to supplierPrint check

Looks like

object-oriented!!

Page 116: Chapter 12: Lists

Programming and Problem Solving With Java 116

Computer Security: IndividualChoose a good password

Shouldn’t be easy to guessDon’t use name of friend, pet, hometown, ...Don’t use a word in EnglishShould be easy to remember, but nonsensical to others

How to choose a passwordUse a mnemonic (“The frog jumped up and kicked the

horse.” Tfjuakth)Concatenate two unrelated words (“cube” + “branch”

cubebranch)Keep your password safe

Don’t write it down anywhereDon’t let others user your account

Page 117: Chapter 12: Lists

Programming and Problem Solving With Java 117

Computer Security: IndividualEncryption

Scrambles data according to an encryption keyMakes data useless to othersMust use decryption key to get original data back

Encryption by rotation

Plaintext: “This is a test.”Encrypted text (key of 3): “Wklv%lv%whvw1”

Common encryption techniquesDESBlowfishPGP

F G H I J K LA B C D E ...

Page 118: Chapter 12: Lists

Programming and Problem Solving With Java 118

Computer Security: IndividualProtect against viruses

Use virus protection programsKeep their virus lists current

Protect against fire, flood, theft InsuranceBackup

Back up your dataCopy to diskette, Zip disk, tapeFull backup: all the data on the computer Incremental backup: changes since last full backup

Page 119: Chapter 12: Lists

Programming and Problem Solving With Java 119

Computer Security: IndividualBackup procedure

Have at least two backups -- one offsite

Newest fullbackupon tape

Previousfull backup

on tape

Previousincremental

backupon floppies

Ready forreuse

Ready forreuse

Newestincremental

backupon floppies