CS 272 Exam 2
Suppose that i is an Iterator object. Write a small piece of Java code that uses i.hasNext and i.next to print all the Objects of i to System.out.
// assuming i is an iterator object already defined, while (i.hasNext()) { System.out.println(i.next().toString()); }
13. public void listInsertZero(IntNode previous) { // Precondition: previous is a reference to a node on a linked list. // Postcondition: A new node has been added to the list after // the node that previous refers to. The new node contains 0.
// creating new node IntNode newNode = new IntNode(0); // pointing the next of newNode to next of previous newNode.link = previous.link; // pointing previous next to newNode previous.link = newNode; }
Here is an INCORRECT pseudocode for the algorithm which is supposed to determine whether a sequence of parentheses is balanced: declare a character stack while ( more input is available) { read a character if ( the character is a '(' ) push it on the stack else if ( the character is a ')' and the stack is not empty ) pop a character off the stack else print "unbalanced" and exit } print "balanced" Which of these unbalanced sequences does the above code think is balanced? A. ((()) B. ())(() C. (()())) D. (()))()
A. ((())
Suppose that x and y are reference variables and a program activates x.equals(y). What occurs if x is the null reference? A. A NullPointerException occurs B. It always returns true. C. It always returns false. D. It returns true if y is also a null reference; otherwise it returns false.
A. A NullPointerException occurs
In the linked list implementation of the stack class, where does the push method place the new entry on the linked list? A. At the head B. At the tail C. After all other entries that are greater than the new entry. D. After all other entries that are smaller than the new entry.
A. At the head
Suppose that obj is an Object variable, and consider these two possible assignments: obj = new Integer(42); obj = new Double(42.0); Both assignments compile correctly. Select the true statement about what happens at run time: A. Both assignments will run with no errors, regardless of which one occurs first. B. Both assignments will run with no errors, but only if the Integer assignment occurs first. C. Both assignments will run with no errors, but only if the Double assignment occurs first. D. A run-time exception occurs with either statement.
A. Both assignments will run with no errors, regardless of which one occurs first.
Which of the following expressions evaluates to true with approximate probability equal to P? (P is double and 0 <= P <= 1). A. Math.random() < P B. Math.random() > P C. Math.random() < P * 100 D. Math.random() > P * 100
A. Math.random() < P
What is the value of the postfix expression 6 3 2 4 + - *: A. Something between -15 and -100 B. Something between -5 and -15 C. Something between 5 and -5 D. Something between 5 and 15 E. Something between 15 and 100
A. Something between -15 and -100
I am going to execute this code with THREE pushes and ONE pop: IntStack s = new IntStack( ); s.push(1); s.push(2); s.push(3); System.out.println(s.pop( )); Suppose that s is represented by a linked list. Draw the state of the private member variables of s after the above code: _______ head| | |_______|
head| 2 | → 1 | null
Suppose that x is an Object variable. Write a small piece of Java code that will print the message "Leopold is cool" provided that x is actually a reference to an object of the Integer wrapper class.
if (x.getClass ().getName ().equals (Integer.getClass ().getName ()) { System.out.println ("Leopold is cool"); }
Suppose that p is a reference to an IntNode in a linked list, and it is not the tail node. What are the steps to removing the node after p? Use one short English sentence for each step.
1. Take a temparary pointer variable (tmp) of type node and assign p's next nodes address in tmp. 2. Make next of tmp as p's next. 3. free the node pointed by tmp
Implement the following method as a new static method for the IntNode class. (Use the usual Node definition with instance variables called data and link.) public static boolean isOn(IntNode head, IntNode p) // Precondition: head is the head reference of a linked list // (which might be empty, or might be non-empty). The parameter p // is a non-null reference to some IntNode on some linked list. // Postcondition: The return value is true if p actually points to // one of the IntNodes in the head's linked list. For example, // p might point to the head node of this list, or the second node, // or the third node, and so on. Otherwise the return value is // false. None of the nodes on any lists are changed.
12. // traversing through linked list while(head != null){ if (head == p) // p points to link in list return true; head = head.link; } return false; // not found }
I am going to execute this code with THREE pushes and ONE pop: IntStack s = new IntStack( ); s.push(1); s.push(2); s.push(3); System.out.println(s.pop( )); Suppose that s is represented by a partially filled array. Draw the state of the private instance variables of s after the above code: _______ __________________________________ manyItems| | data| | | | | | |_______| |______|______|______|______|______|... [0] [1] [2] [3] [4]
2 | →1 | → 2 | null
Consider this code using the ArrayBag from Section 5.2: Integer i = new Integer(42); Integer j = new Integer(43); ArrayBag b = new ArrayBag( ); // Add two i's and one j: b.add(i); b.add(i); b.add(j); Draw a diagram showing the reference variables i and j with their pointers to Integer objects, and also show b's data array with its pointers after these add statements.
5.8 ------ ------ i ----> | 42 | <--------+--. | b.data[0] ------ <-- ------ \_____|__. | b.data[1] ------ ------ j ----> | 43 | <--------+--. | b.data[2] ------ ------
An array of queues can be used to implement a priority queue, with each possible priority corresponding to its own element in the array. When is this implementation not feasible? A. When the number of possible priorities is huge. B. When the number of possible priorities is small. C. When the queues are implemented using a linked list. D. When the queues are implemented with circular arrays.
A. When the number of possible priorities is huge.
Suppose that obj is an Object variable and s is a String variable. Which of the following statements is a correctly-compiling widening conversion? Don't worry about possible run-time exceptions. A. obj = s; B. s = obj; C. s = (String) obj; D. Two or more answers are correct.
A. obj = s;
Consider this code using the ArrayBag of Section 5.2 and the Location class from Chapter 2. What is the output? Location i = new Location(0, 3); Location j = new Location(0, 3); b.add(i); b.add(j); System.out.println(b.countOccurrences(i)); A. 0 B. 1 C. 2 D. 3
B. 1
Consider the usual algorithm for determining whether a sequence of parentheses is balanced. Suppose that you run the algorithm on a sequence that contains 2 left parentheses and 3 right parentheses (in some order). What is the maximum number of parentheses that will ever appear on the stack AT ONE TIME during the computation? A. 1 B. 2 C. 3 D. 4 E. 5 or more
B. 2
n the linked list implementation of the queue class, where does the insert method place the new entry on the linked list? A. At the head B. At the tail C. After all other entries that are greater than the new entry. D. After all other entries that are smaller than the new entry.
B. At the tail
Consider the implementation of the Stack using a partially-filled array. What goes wrong if we try to store the top of the Stack at location [0] and the bottom of the Stack at the last used position of the array? A. Both peek and pop would require linear time. B. Both push and pop would require linear time. C. The Stack could not be used to check balanced parentheses. D. The Stack could not be used to evaluate postfix expressions.
B. Both push and pop would require linear time.
Consider the implementation of the Queue using a circular array. What goes wrong if we try to keep all the items at the front of a partially-filled array (so that data[0] is always the front). A. The constructor would require linear time. B. The getFront method would require linear time. C. The insert method would require linear time. D. The isEmpty method would require linear time.
B. The getFront method would require linear time.
Suppose getFront is called on a priority queue that has exactly two entries with equal priority. How is the return value of getFront selected? A. One is chosen at random. B. The one which was inserted first. C. The one which was inserted most recently. D. This can never happen (violates the precondition)
B. The one which was inserted first.
Suppose that obj is an Object variable and that it refers to an Integer object. If s is a String variable, then which statement is correct about the assignment "s = (String) obj;"? A. The statement will not compile. B. The statement will compile, but there will be a run-time exception. C. The statement will compile and run with no exception.
B. The statement will compile, but there will be a run-time exception.
Which of the following stack operations could result in stack underflow? A. is_empty B. pop C. push D. Two or more of the above answers
B. pop
If data is a circular array of CAPACITY elements, and rear is an index into that array, what is the formula for the index after rear? A. (rear % 1) + CAPACITY B. rear % (1 + CAPACITY) C. (rear + 1) % CAPACITY D. rear + (1 % CAPACITY)
C. (rear + 1) % CAPACITY
Consider this code using the ArrayBag of Section 5.2 and the Location class from Chapter 2. What is the output? Location i = new Location(0, 3); Location j = new Location(0, 3); b.add(i); b.add(j); // Change the Location j: j.shift(1, 0); System.out.println(b.countOccurrences(i)); A. 0 B. 1 C. 2 D. 3
C. 2
Consider the usual algorithm for determining whether a sequence of parentheses is balanced. What is the maximum number of parentheses that will appear on the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))? A. 1 B. 2 C. 3 D. 4 E. 5 or more
C. 3
Consider the usual algorithm to convert an infix expression to a postfix expression. Suppose that you have read 10 input characters during a conversion and that the stack now contains these symbols: | | | + | | ( | bottom |___*___| Now, suppose that you read and process the 11th symbol of the input. Draw the stack for the case where the 11th symbol is: A. A number: B. A left parenthesis: C. A right parenthesis: D. A minus sign: E. A division sign:
C. A right parenthesis
One difference between a queue and a stack is: A. Queues require linked lists, but stacks do not. B. Stacks require linked lists, but queues do not. C. Queues use two ends of the structure; stacks use only one. D. Stacks use two ends of the structure, queues use only one.
C. Queues use two ends of the structure; stacks use only one.
I have implemented the queue with a circular array, keeping track of front, rear, and manyItems (the number of items in the array). Suppose front is zero, and rear is one less than the current capacity. What can you tell me about manyItems? A. manyItems must be zero. B. manyItems must be equal to the current capacity. C. manyItems could be zero or the capacity, but no other values could occur. D. None of the above.
C. manyItems could be zero or the capacity, but no other values could occur.
The operation for removing an entry from a stack is traditionally called: A. delete B. peek C. pop D. remove
C. pop
Suppose that obj is an Object variable and s is a String variable. Which of the following statements is a correctly-compiling narrowing conversion? Don't worry about possible run-time exceptions. A. obj = s; B. s = obj; C. s = (String) obj; D. Two or more answers are correct.
C. s = (String) obj;
Consider the following pseudocode: declare a stack of characters while ( there are more characters in the word to read ) { read a character push the character on the stack } while ( the stack is not empty ) { pop a character off the stack write the character to the screen } What is written to the screen for the input "carpets"? A. serc B. carpets C. steprac D. ccaarrppeettss
C. steprac
Which of the following applications may use a stack? A. A parentheses balancing program. B. Keeping track of local variables at run time. C. Syntax analyzer for a compiler. D. All of the above.
D. All of the above.
I have implemented the queue with a linked list, keeping track of a front node and a rear node with two reference variables. Which of these reference variables will change during an insertion into an EMPTY queue? A. Neither changes B. Only front changes. C. Only rear changes. D. Both change.
D. Both change.
If the characters 'D', 'C', 'B', 'A' are placed in a queue (in that order), and then removed one at a time, in what order will they be removed? A. ABCD B. ABDC C. DCAB D. DCBA
D. DCBA
In the circular array version of the Queue class, which operations require linear time for their worst-case behavior? A. getFront B. insert when the capacity has not yet been reached C. isEmpty D. None of these operations require linear time.
D. None of these operations require linear time.
In the linked-list version of the Queue class, which operations require linear time for their worst-case behavior? A. getFront B. insert C. isEmpty D. None of these operations require linear time.
D. None of these operations require linear time.
Entries in a stack are "ordered". What is the meaning of this statement? A. A collection of Stacks can be sorted. B. Stack entries may be compared with the '<' operation. C. The entries must be stored in a linked list. D. There is a first entry, a second entry, and so on.
D. There is a first entry, a second entry, and so on.
Suppose we have an array implementation of the stack class, with ten items in the stack stored at data[0] through data[9]. The CAPACITY is 42. Where does the push method place the new entry in the array? A. data[0] B. data[1] C. data[9] D. data[10]
D. data[10]
Suppose we have a circular array implementation of the queue class, with ten items in the queue stored at data[2] through data[11]. The current capacity is 42. Where does the insert method place the new entry in the array? A. data[1] B. data[2] C. data[11] D. data[12]
D. data[12]
The operation for adding an entry to a stack is traditionally called: A. add B. append C. insert D. push
D. push
In the array version of the Stack class, which operations require linear time for their worst-case behavior? A. is_empty B. peek C. pop D. push when the stack is below capacity E. None of these operations require linear time.
E. None of these operations require linear time.
In the linked-list version of the Stack class, which operations require linear time for their worst-case behavior? A. is_empty B. peek C. pop D. push E. None of these operations require linear time.
E. None of these operations require linear time.
Compare the worst-case big-O time analysis for these two methods: The remove method for the Sequence that is implemented using an array, and the remove method for the Sequence that is implemented using a linked list.
For an array, remove is O(n) as it will require copying possibly all of remaining n-1when the first element of the array is removed. For a doubly linked-list, O(1) again. We simply update the points of the previous and next elements.
Compare the worst-case big-O time analysis for these two methods: The addBefore method for the Sequence that is implemented using an array, and the addBefore method for the Sequence that is implemented using a linked list.
For an array, the worst case time is linear, O(n), because the element at the index i where addBefore inserts must shift all the elements in the array in the case of inserting at the beginning. For a linked-list the worst case time is constant, O(1), if we have a pointer/reference to the node and the list is doubly linked. Otherwise, it is O(n), because we have to find locate the element before which to insert in order to update the links!
Suppose that p, q, and r are all references to nodes in a linked list with 15 nodes. The variable p refers to the first node, q refers to the 8th node, and r refers to the last node. Write a few lines of code that will make a new copy of the list. You code should set THREE new variables called x, y, and z so that: x refers to the first node of the copy, y refers to the 8th node of the copy, and z refers to the last node of the copy. Your code may NOT contain any loops, but it can use the other IntNode methods.
IntNode[]array; Array=IntNode.listPart(p.q); X=array[0]; Y=array[1]; Array=IntNode.listPart(q.link, r); Y.link=array[0]; Z=array[1];
Suppose that b and c are Integer objects. A typical use of the clone method looks like this: b = (Integer) c.clone( ); Write a short clear explanation of why the (Integer) type cast is required in this typical example.
Narrowing Conversion: occurs when we take a less specific type (superclass) and attempt to assign it to a more specific type (subclass), which requires explicit casting.
Compare the worst-case big-O time analysis for these two methods: The remove method for the Bag that is implemented using a fixed-sized array, and the remove method for the Bag that is implemented using a linked list.
O(n) and O(1) respectively
Compare the worst-case big-O time analysis for these two methods: The add method for the Bag that is implemented using an array, and the add method for the Bag that is implemented using a linked list.
O(n) and O(1) respectively. Note that this method is called removeCurrent in the text
Implement the following method as a new static method for the IntNode class. (Use the usual IntNode class with instance variables called data and link.) public static int count42s(IntNode head) // Precondition: head is the head reference of a linked list. // The list might be empty or it might be non-empty. // Postcondition: The return value is the number of occurrences // of 42 in the data field of a node on the linked list. // The list itself is unchanged.
Public static int count42s(IntNode head) { int count=0; IntNode cursor; For(cursor=head; cursor!=null; cursor=cursor.link;) { if(cursor.data==42) count++; return count; }
Suppose that i and j are both Integer objects (using the Integer wrapper class). Write a statement that will print the sum of i and j.
System.out.println(i.intValue() + j.intValue());
Describe one primary advantage of an external iterator versus an internal iterator.
The advantage of external iterator is that, many iterators can be made active simultaneously on the existing or same object.
What are the steps to inserting a new item at the head of a linked list? Use one short English sentence for each step.
The new node is always added before the head of the given Linked List. And newly added node becomes the new head of the Linked List. For example if the given Linked List is 10->15->20->25 and we add an item 5 at the front, then the Linked List becomes 5->10->15->20->25. Let us call the function that adds at the front of the list is push(). The push() must receive a pointer to the head pointer, because push must change the head pointer to point to the new node
Will the following code compile correctly? Will it run without errors? Object obj; Integer i; String s = new String("forty-two"); obj = s; i = (Integer) obj;
There is no compilation error in this code. But, It will give you the error in run time. Because string "forty-two" can not be converted to integer.
What kind of list is best to answer questions such as "What is the item at position n?" a. Lists implemented with an array b. Doubly-linked lists c. Singly-linked lists d. Doubly-linked or singly-linked lists are equally best
a. Lists implemented with an array
In the linked list version of the Bag class an instance variable manyNodes is used to keep track of how long the linked list is. Why not just make a call to the IntNode method listLength()? a. The listLength() method is )(n) and the alternative is O(1) b. The listLength() method is private c. The listLength() method results in an infinite loop for circular lists d. The listLength() method works only for lists of integers
a. The listLength() method is )(n) and the alternative is O(1)
Suppose cursor refers to a node in a linked list (using the Node class with instance variables called data and link). What boolean expression will be true when cursor refers to the tail node of the list a. (cursor == null) b. (cursor.link == null) c. (cursor.data == null) d. cursor.data == 0.0) e. none of the above
b. (cursor.link == null)
Which Boolean expression indicates whether the numbers in two nodes (p and q) are the same. Assume that neither p nor q is null a. p == q b. p.data == q.data c. p.link == q.link d. none of the above
b. p.data == q.data
Suppose that p is a reference variable that contains the null reference. What happens at runtime if the program tries to activate a method of p? a. illegalArgumentException b. IllegalStateException c. NullPointerException d. the results are unpredictable
c. NullPointerException
Suppose cursor refers to a linked list (using the IntNode class with instance variables called data and link). What statement changes cursor so that it refers to the next node a. cursor++ b. cursor = link; c. cursor += link; d. cursor = cursor.link;
d. cursor = cursor.link;
Complete the body of this method. You do not need to check the precondition. You may use the CharStack class. public static boolean balanced(String p) // Precondition: Each character of p is '(', ')', '{' or '}'. // Postcondition: The method returns true if the characters form a // sequence of correctly balanced parentheses with each '(' matching // a ')' and each '{' matching a '}'. Note that a sequence such as // ( { ) } is NOT balanced because when we draw lines to match the // parentheses to their partners, the lines cross each other. On the // other hand, ( { } ) and { ( ) } are both balanced.
declare a character stack while ( more input is available) { read a character if ( the character is a '(' or '{' ) push it on the stack else if ( the character is a ')' or '}' and the stack is not empty ) pop a character off the stack else print "unbalanced" and exit } print "balanced"
Consider this code from the start of a Java method: Object obj; String good = new String("Study hard!"); String bad = new String("Party hard!"); obj = good; good = bad; ... Write one more assignment statement that can appear after these to reset the good String back to its original value. Is your assignment a widening conversion or a narrowing conversion?
obj = (String) obj; Narrowing
Write some lines of code that declares an Integer object, using the Integer wrapper class. Assign the value 42 to this object, then copy this value from the Integer object to an ordinary int variable.
public class MyBasicInteger { public static void main(String a[]){ int i = 10; Integer intg = new Integer(i); System.out.println(intg); String no = "223"; Integer num = new Integer(no); System.out.println(num); } }
Here is some code to count the number of occurrences of a specific target integer in an array of integers: int i; int answer = 0; for (i = 0; i < data.length; i++) if (data[i] == target) answer++; At the end of the code, the value of answer indicates how many times target appears in the array. Rewrite the code so that it works correctly when the data array is an array of objects and target is a non-null reference to an object with an equals method.
public class findingTarget { public static void main(String[] args) { String target = new String("Bob1"); for (int i = 0; i < data.length; i++) if (data[i].equals(target)) answer++; } System.out.println("Total count is : " + answer); }
Implement the following method as a new static method for the IntNode class. (Use the usual IntNode definition with instance variables called data and link.) public static boolean has42(IntNode head) // Precondition: head is the head reference of a linked list. // The list might be empty or it might be non-empty. // Postcondition: The return value is true if the list has at least // one occurrence of the number 42 in the data part of a node.
public static boolean has42(IntNode head) int count=0; IntNode cursor; For(cursor=head; cursor!=null; cursor=cursor.link;) { If(cursor.data==42) Return true; } Return false; }
Implement the following method as a new stati method for the IntNode class. (Use the usual IntNode definition with instance variables called data and link.) public static int sum(IntNode head) // Precondition: head is the head reference of a linked list. // The list might be empty or it might be non-empty. // Postcondition: The return value is the sum of all the data components // of all the nodes. NOTE: If the list is empty, the method returns 0.
public static int sum(IntNode head) int count=0; IntNode cursor; For(cursor=head; cursor!=null; cursor=cursor.link;) Count+=cursor.data; Return count; }
Suppose that a and b are IntNode variables. Write one clear sentence to tell me when the expression (a==b) will be true.
when the tail of the both nodes points to the same memory