Wrap-Up

Answers to Self Review Exercises

25.1

a) False. A queue is a first-in, first-out data structurethe first item added is the first item removed. b) False. In general, trees may have as many child nodes per node as is necessary. Only binary trees are restricted to no more than two child nodes per node. c) True. d) False. Linked-list nodes are logically contiguous, but they need not be stored in a physically contiguous memory space. e) False. Those are the primary operations of a queue. The primary operations of a stack are push and pop. f) True.

25.2

a) self-referential. b) new. c) stack. d) first-in, first-out (FIFO). e) queue. f) tree. g) binary. h) preorder.

Exercises

25.3

Write a program that merges two ordered list objects of integers into a single ordered list object of integers. Method Merge of class ListMerge should receive references to each of the list objects to be merged and should return a reference to the merged list object.

25.4

Write a program that inputs a line of text and uses a stack object to print the line reversed.

25.5

Write a program that uses a stack to determine whether a string is a palindrome (i.e., the string is spelled identically backward and forward). The program should ignore capitalization, spaces and punctuation.

25.6

Stacks are used by compilers in the process of evaluating expressions and in generating machine language code. In this and the next exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses.

Humans generally write expressions like 3 + 4 and 7/9, in which the operator (+ or / here) is written between its operandsthis is called infix notation. Computers "prefer" postfix notation, in which the operator is written to the right of its two operands. The preceding infix expressions would appear in postfix notation as 3 4 + and 7 9 /, respectively.

To evaluate a complex infix expression, a compiler would first convert the expression to postfix notation, then evaluate the postfix version of the expression. Each of these algorithms requires only a single left-to-right pass of the expression. Each algorithm uses a stack object in support of its operation, and in each algorithm the stack is used for a different purpose.

In this exercise, you will write a C# version of the infix-to-postfix conversion algorithm. In the next exercise, you will write a C# version of the postfix expression evaluation algorithm. In a later exercise, you will discover that code you write in this exercise can help you implement a complete working compiler.

Write class InfixToPostfixConverter to convert an ordinary infix arithmetic expression (assume a valid expression is entered), with single-digit integers, such as

(6 + 2) * 5 - 8 / 4  

to a postfix expression. The postfix version of the preceding infix expression (note that no parentheses are needed) is

6 2 + 5 * 8 4 / -  

The program should read the expression into StringBuilder infix, then use class StackInheritance (implemented in Fig. 25.13) to help create the postfix expression in StringBuilder postfix. The algorithm for creating a postfix expression is as follows:

  1. Push a left parenthesis '(' on the stack.
  2. Append a right parenthesis ')' to the end of infix.
  3. While the stack is not empty, read infix from left to right and do the following:

    If the current character in infix is a digit, append it to postfix.

    If the current character in infix is a left parenthesis, push it onto the stack.

    If the current character in infix is an operator:

    Pop operators (if there are any) at the top of the stack while they have equal or higher precedence than the current operator, and append the popped operators to postfix.

    Push the current character in infix onto the stack.

    If the current character in infix is a right parenthesis:

    Pop operators from the top of the stack and append them to postfix until a left parenthesis is at the top of the stack.

    Pop (and discard) the left parenthesis from the stack.

The following arithmetic operations are allowed in an expression:

+

addition

-

subtraction

*

multiplication

/

division

^

exponentiation

%

modulus

 

Some of the methods you may want to provide in your program follow:

  1. Method ConvertToPostfix, which converts the infix expression to postfix notation.
  2. Method IsOperator, which determines whether c is an operator.
  3. Method Precedence, which determines whether the precedence of operator1 (from the infix expression) is less than, equal to or greater than the precedence of operator2 (from the stack). The method returns true if operator1 has lower precedence than or equal precedence to operator2. Otherwise, false is returned.

25.7

Write class PostfixEvaluator, which evaluates a postfix expression (assume it is valid) such as

6 2 + 5 * 8 4 / -  

The program should read a postfix expression consisting of digits and operators into a StringBuilder. Using the stack class from Exercise 25.6, the program should scan the expression and evaluate it. The algorithm (for single-digit numbers) is as follows:

  1. Append a right parenthesis (')') to the end of the postfix expression. When the rightparenthesis character is encountered, no further processing is necessary.
  2. When the right-parenthesis character has not been encountered, read the expression from left to right.

    If the current character is a digit, do the following:

    Push its integer value on the stack (the integer value of a digit character is its value in the computer's character set minus the value of '0' in Unicode).

    Otherwise, if the current character is an operator:

    Pop the two top elements of the stack into variables x and y.

    Calculate y operator x.

    Push the result of the calculation onto the stack.

  3. When the right parenthesis is encountered in the expression, pop the top value of the stack. This is the result of the postfix expression.

[Note: In part (b) above (based on the sample expression at the beginning of this exercises), if the operator is '/', the top of the stack is 4 and the next element in the stack is 8, then pop 4 into x, pop 8 into y, evaluate 8 / 4 and push the result, 2, back on the stack. This note also applies to operator '-'.] The arithmetic operations allowed in an expression are:

+

addition

-

subtraction

*

multiplication

/

division

^

exponentiation

%

modulus

 

You may want to provide the following methods:

  1. Method EvaluatePostfixExpression, which evaluates the postfix expression.
  2. Method Calculate, which evaluates the expression op1 operator op2.

25.8

(Binary Tree Delete) In this exercise, we discuss deleting items from binary search trees. The deletion algorithm is not as straightforward as the insertion algorithm. There are three cases that are encountered when deleting an itemthe item is contained in a leaf node (i.e., it has no children), the item is contained in a node that has one child or the item is contained in a node that has two children.

If the item to be deleted is contained in a leaf node, the node is deleted and the reference in the parent node is set to null.

If the item to be deleted is contained in a node with one child, the reference in the parent node is set to reference the child node and the node containing the data item is deleted. This causes the child node to take the place of the deleted node in the tree.

The last case is the most difficult. When a node with two children is deleted, another node in the tree must take its place. However, the reference in the parent node cannot be assigned to reference one of the children of the node to be deleted. In most cases, the resulting binary search tree would not adhere to the following characteristic of binary search trees (with no duplicate values): The values in any left subtree are less than the value in the parent node, and the values in any right subtree are greater than the value in the parent node.

Which node is used as a replacement node to maintain this characteristicthe node containing the largest value in the tree less than the value in the node being deleted or the node containing the smallest value in the tree greater than the value in the node being deleted? Let us consider the node with the smaller value. In a binary search tree, the largest value less than a parent's value is located in the left subtree of the parent node and is guaranteed to be contained in the rightmost node of the subtree. This node is located by walking down the left subtree to the right until the reference to the right child of the current node is null. We are now referencing the replacement node, which is either a leaf node or a node with one child to its left. If the replacement node is a leaf node, the steps to perform the deletion are as follows:

  1. Store the reference to the node to be deleted in a temporary reference variable.

     

  2. Set the reference in the parent of the node being deleted to reference the replacement node.

     

  3. Set the reference in the parent of the replacement node to null.

     

  4. Set the reference to the right subtree in the replacement node to reference the right subtree of the node to be deleted.

     

  5. Set the reference to the left subtree in the replacement node to reference the left subtree of the node to be deleted.

     

The deletion steps for a replacement node with a left child are similar to those for a replacement node with no children, but the algorithm also must move the child into the replacement node's position in the tree. If the replacement node is a node with a left child, the steps to perform the deletion are as follows:

  1. Store the reference to the node to be deleted in a temporary reference variable.

     

  2. Set the reference in the parent of the node being deleted to reference the replacement node.

     

  3. Set the reference in the parent of the replacement node reference to the left child of the replacement node.

     

  4. Set the reference to the right subtree in the replacement node reference to the right subtree of the node to be deleted.

     

  5. Set the reference to the left subtree in the replacement node to reference the left subtree of the node to be deleted.

     

Write method DeleteNode, which takes as its argument the value of the node to be deleted. Method DeleteNode should locate in the tree the node containing the value to be deleted and use the algorithms discussed here to delete the node. If the value is not found in the tree, the method should print a message that indicates whether the value is deleted. Modify the program of Fig. 25.21 to use this method. After deleting an item, call methods InorderTraversal, PreorderTraversal and PostorderTraversal to confirm that the delete operation was performed correctly.

25.9

(Level-Order Binary Tree Traversal) The program of Fig. 25.21 illustrated three recursive methods of traversing a binary treeinorder, preorder, and postorder traversals. This exercise presents the level-order traversal of a binary tree, in which the node values are printed level-by-level, starting at the root-node level. The nodes on each level are printed from left to right. The level-order traversal is not a recursive algorithm. It uses a queue object to control the output of the nodes. The algorithm is as follows:

  1. Insert the root node in the queue.
  2. While there are nodes left in the queue, do the following:

    Get the next node in the queue.

    Print the node's value.

    If the reference to the left child of the node is not null:

    Insert the left child node in the queue.

    If the reference to the right child of the node is not null:

    Insert the right child node in the queue.

Write method LevelOrderTraversal to perform a level-order traversal of a binary tree object. Modify the program of Fig. 25.21 to use this method. [Note: You also will need to use the queueprocessing methods of Fig. 25.16 in this program.]

Generics

Категории