QUIZ 2 Warm-up Questions
.pdf
keyboard_arrow_up
School
Pennsylvania State University *
*We aren’t endorsed by this school
Course
132
Subject
Computer Science
Date
Apr 3, 2024
Type
Pages
5
Uploaded by ChancellorEagle4123
CMPSC-132: Practice Exercises Question 1:
Write the Python code for finding the second-to-last (item before the last) node in a Singly Linked list in which the last node is indicated by a next
reference of None. If there is no second-to-last node, return None. Question 2
: Assume you have a Doubly Linked List with the head node and at least one other internal node C which is not the last node. You may assume that each node has a next
pointer and prev
pointer. Write few lines of code to accomplish the following. You may NOT swap data to accomplish any of the following operations. Remember that for each operation, you need to manipulate at least two pointers, next
and prev
. a) Delete the head Node b) Swap head and C nodes, you cannot swap data Question 3:
Recall the Stack data structure discussed in Module 5. You were asked to implement such structure in Homework 3. Such data structure contained a reference to the top node in the stack and can perform the operations len, isEmpty, push, pop and peek only. Write the Python code for the function smallest_at_top(stack_object) that takes a Stack object as a parameter and determines which value in stack_object is the smallest and move that Node to the top of the stack while leaving the remainder of the stack in its original order. For example, if the stack contains the elements 23, 72, 94, 3, 1, 60 (where 23 is the top Node and 60 is the bottom Node) then a call to smallest_at_top (stack_object) will update the original stack to 1, 23, 72, 94, 3, 60 (where 1 is the top Node and 60 is the bottom Node) and returns nothing. Your code may only declare Stack or scalar variables (int, float) if needed. You are not allowed to declare other variables such as Python lists, linked lists, dictionaries, etc., or use other methods or Classes from the Python library. You can assume the stack contains unique numerical values. When the stack is empty, smallest_at_top (stack_object) returns None def smallest_at_top(stack_object): ''' >>> myStack=Stack() >>> myStack.push(55) >>> myStack.push(98) >>> myStack.push(-2.5) >>> myStack.push(3) >>> myStack.push(156) >>> myStack.push(9) >>> myStack.push(56.5) >>> myStack Top:Node(56.5) Stack: 56.5 9 156 3 -2.5 98 55 >>> smallest_at_top(myStack) >>> myStack Top:Node(-2.5) Stack: -2.5 56.5 9 156 3 98 55 '''
Question 4:
Write the implementation for the pop() method for a Doubly Linked List with a) a reference to the tail node and b) no reference to the tail node. The Node class is defined as: class Node: def __init__(self, value): self.value = value self.next = None self.previous = None def __str__(self): return f"Node({self.value})" __repr__ = __str__ Question 5:
Below is the partial implementation of a FIFO Queue using only Stacks. The constructor, isEmpty and enqueue methods have been implemented for you and should not be modified. Write the implementation of the dequeue method for the Queue class using only stack_1 and stack_2 operations only. You are not allowed to use Python lists. class Queue: def __init__(self): self.stack_1=Stack() self.stack_2=Stack() def isEmpty(self): if self.stack_1.isEmpty() and self.stack_2.isEmpty(): return True return False def enqueue(self, value): self.stack_1.push(value) def
dequeue(self):
Question 6: Consider a real-time stock trading platform where traders need to quickly respond to market changes. In such a platform, each trader might have a list of buy or sell orders they've placed, which need to be processed in a specific order (LIFO - Last In, First Out) as market conditions change. However, traders also need to keep track of their most advantageous (minimum) price point among their active orders to make informed decisions swiftly. Design a class `StockTrader` that supports all three of these operations without requiring any looping. Hint
: consider having two stacks, one that stores the stocks in the order they come in, and one that keeps a "running minimum". Question 7: Write the method double_them that takes a queue and replaces every node in the queue with two occurrences of that node. For example, suppose a queue contains the following values: 3 -> 7.5 -> “
1
”
-> 14-> 9, when 3 is the head and 9 the tail. After the method ends the queue should contain the following values: 3 -> 3 -> 7.5 -> 7.5 -> “
1
”
-> “
1
”
-> 14-> 14 -> 9 ->9 (3 is head and 9 tail). Notice that you must preserve the original order. You may use one queue for additional storage. Question 8:
Complete the definition of the get_sum method in the BinaryTree class. This method returns the sum of the values contained in all of the Nodes of the binary tree with root node
. It does not modify the original tree. You can assume the values of the nodes are numeric. You are not allowed to copy values of the Nodes into other data structures class Node: def __init__(self, value): self.value = value self.left = None self.right = None def __str__(self): return ("Node({})".format(self.value)) __repr__ = __str__ class BinaryTree: def __init__(self): self.root = None def get_sum(self, start): ''' For the binary tree shown in the picture: >>> x.get_sum(x.root) 55 >>> x.get_sum(x.root.left) 31 >>> x.get_sum(x.root.left.right) 22 '''
Question 9:
Write the implementation of the __contains__ method in the BinaryTree class that returns True if value is present in the tree, False otherwise. Note that the tree is not necessarily a binary search tree. Question 10:
Write the implementation of the reverse method in the LinkedList class discussed and implemented in Module 5. This method reverses the list in-place (modifies the original list).
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Questions
In c++ please explain the
code
Q1. Given a 'key', delete the first occurrence of
this key in the linked list.
Iterative Method:
To delete a node from the linked list, we need
to do the following steps.
1) Find the previous node of the node to be
deleted.
2) Change the next of the previous node.
3) Free memory for the node to be deleted.
arrow_forward
Complete the code fragment for all three cases
Please write python code
arrow_forward
kindly don't copy the code from other websites because it's incorrect.. Thanks
Linked Lists
C Programming :
Develop a Student Information System. The system need to implement the
insertNode(), deleteNode() and displayList() functions. The insertNode() function is
used to insert a new node of student record to the linked list. Assume that the input
id is always unique, thus the linked list shall contain the student records with their
respective id numbers are in ascending order. The displayList() function is used to
display the list after inserting new node and/or after deleting a node. Please refer to
the given structure definition shown in Figure 1, Your system interface should
consider a few element such as user friendly, attractive and appropriate word. You
may add more suitable data in the structure but limited to not more than 3.
The deleteNode() function is used to remove a record of the targeted id from the
linked list. The deleteNode() function shall return the target id if the…
arrow_forward
TROUBLESHOOT my PYTHON code, please :)
The code of a sequential search function is shown on textbook page 60. In fact, if the list is already sorted, the search can halt when the target is less than a given element in the list. For example, given my_list = [2, 5, 7, 9, 14, 27], if the search target is 6, the search can halt when it reaches 7 because it is impossible for 6 to exist after 7. Define a function linearSearchSorted, which is used to search a sorted list. This function displays the position of the target item if found, or 'Target not found' otherwise. It also displays the elements it has visited. To test your function, search for these targets in the list [2, 5, 7, 9, 14, 27]: 2, 6, 14, 27 and 28.
Expected output:
List: [2, 5, 7, 9, 14, 27]
Search target: 2
Elements visited: 2
Target found at position 0
Search target: 6
Elements visited: 2 5 7
Target not found
Search target: 14
Elements visited: 2 5 7 9 14
Target found at position 4
Search target: 27
Elements visited: 2…
arrow_forward
TOPIC: Big-O Notation
arrow_forward
Old MathJax webview
Old MathJax webview
In Java Some methods of the singly linked list listed below can be implemented efficiently (in different respects) (as opposed to an array or a doubly linked list), others not necessarily which are they and why? b. Implement a function to add an element before the first element. c. Implement a function to add an item after the last one element. d. Implement a function to output an element of the list. e. Implement a function to output the entire list. f. Implement a function to output the number of elements. G. Implement a function to delete an item. H. Implement a function to clear the entire list. I. Implement functionality to search for one or more students by first name, last name, matriculation number or course of study. J. Implement functionality to sort the records of the student, matriculation number and course according to two self-selected sorting methods.
arrow_forward
Python code
screenshot and output is must
arrow_forward
Part 2: Advanced Queue (optional)
Exercise 1. Priority Queue
Based on the above program, create a function void priorityQueue (queue q), which
accept current queue and insert new priority queue (int) at the front of the current queue
Thus all items in current queue after inserting the new priority item will be moved. Simulate
the priority queue by using random Boolean event.
Pseudo Code:
function priorityQueue (queue q)
boolean priority = random Boolean //random Boolean event
queue tmp
if priority then
get front q
pop front to tmp
while q is not empty
get front from q
new = front+1
pop from q
push new to tmp
end while
else
return q
return tmp
end function
arrow_forward
Linked List
Write a DETAILED algorithm length to count the number of nodes in a singly linked list p, where p points to the first node in the list. The last node has link field NULL. Assume that each node has two fields: data and link. Account for the range of all possible linked list lengths.
Needs to be in detailed and code in C PROGRAM would be helpful!
arrow_forward
True/False Select true or false for the statements below. Explain your answers if you like to receive partial credit.
3) Which of the following is true about the insertBeforeCurrent function for a CircularLinked List (CLL) like you did in programming exercise 1?a. If the CLL is empty, you need to create the new node, set it to current, andhave its next pointer refer to itselfb. The worst case performance of the function is O(n)c. If you insert a new element with the same data value as the current node, theperformance improves to O(log n)
arrow_forward
Student should be able to develop the programs for queue using arrays and linked list
By Using C++ software.
Exercise 1: Implementation of Queue using Array or Linked list
Consider a real life situation. Formulate a question and then design a simulation that can help
to answer it. Choose one of the following situations:
• Cars lined up at a car wash
• Customers at a grocery store check-out
• Airplanes taking off and landing on a runway
• A bank teller
Be sure to state any assumptions that you make and provide any probabilistic data that must
be considered as part of the scenario.
arrow_forward
2-) In a double linked list, the structure of a node is defined as follows:
struct node {
int employeeNo;
char name[20];
struct node *next;
structnode *prev;
}node;
the nodes in the list are sorted according to employeeNo in ascending order (from smaller to larger ).
Write a function to insert a node with a given name and employeeNo into the list so that the list will
remain the sorted. employeeNo değerine göre kiüçükten büyüğe sıralanmış bir çift bağlı liste olsun.
Verilen bir isim ve employeeNo değerine sahip düğümü listeye sıra bozulmayacak şekilde ekleyen bir
fonksyion yazınız.
arrow_forward
.
arrow_forward
LINKED LIST IMPLEMENTATION
Subject: Data Structure and Algorithm in C++Create a Student Record Management system that can perform the following operations:1) Insert student records2) Delete student record3) Show student record4) Search student record
The student record should contain the following items1) Name of Student2) Student Matriculation ID number3) Course in which the student is enrolled4) Total marks of the student Approach: With the basic knowledge of operations of Linked Lists like insertion, deletion of elements in linked list, the student record management can be created. Below are the functionalities explained that are to be implemented.●Check Record: It is a utility function of creating a record it checks before insertion that the Record Already exist or not. It uses the concept of checking for a Node with given Data in a linked list.-Create Record: It is as simple as creating a new node in the Empty Linked list or inserting a new node in a non-Empty linked list.-Search…
arrow_forward
Write C code that implements a soccer team as a linked list.
1. Each node in the linkedlist should be a member of the team and should contain the following information:
What position they play
whether they are the captain or not
Their pay
2. Write a function that adds a new members to this linkedlist at the end of the list.
arrow_forward
QUESTION:
NOTE: This assignment is needed to be done in OOP(c++/java), the assignment is a part of course named data structures and algorithm.
A singly linked circular list is a linked list where the last node in the list points to the first node in the list. A circular list does not contain NULL pointers.
A good example of an application where circular linked list should be used is a items in the shopping cart
In online shopping cart, the system must maintain a list of items and must calculate total bill by adding amount of all the items in the cart,
Implement the above scenario using Circular Link List. Do Following:
First create a class Item having id, name, price and quantity provide appropriate methods and then Create Cart/List class which holds an items object to represent total items in cart and next pointer Implement the method to add items in the array, remove an item and display all items.
Now in the main do the following
Insert Items in list
Display all items.
Traverse…
arrow_forward
Please don't copy Write a C++ program that uses a linked list implementation The information for each toy product includes the product ID, product name, available quantity and price. Create a linked list node to store the information for each product. Provide a menu to perform the following actions. * Add a new product. Products are sorted according to the product ID in the linked list. * Sell a product. The available quantity of this product is reduced, based on the number of products that have been sold * Check if a product is available * Search if a product is sold by a shop * List the names of productscheaper than 50
arrow_forward
HELP
Write C code that implements a soccer team as a linked list.
1. Each node in the linkedlist should be a member of the team and should contain the following information:
What position they play
whether they are the captain or not
Their pay
2. Write a function that adds a new members to this linkedlist at the end of the list.
arrow_forward
in c please with comments
arrow_forward
kindly don't copy the code from other websites because it's incorrect
arrow_forward
Solve the following Program Using C++ solve it correctly and quickly please.
arrow_forward
Use C++ Programming language:
Design and implement your own linked list class to hold a sorted list of integers in ascending order. The class should have member functions for inserting an item in the list (in ascending order), deleting an item from the list, and searching the list for an item. Note: the search function should return the position of the item in the list (first item at position 0) and -1 if not found.
In addition, it should have member functions to display the list, check if the list is empty, and return the length of the list. Be sure to have a class constructor a class destructor, and a class copy constructor for deep copy. Demonstrate your class with a driver program (be sure to include the following cases: insertion at the beginning, end (note that the list should alway insert in ascending order. However, in your test include a case where the inserted item goes at the beginning of the list), and inside the list, deletion of first item, last item, and an item…
arrow_forward
Fill-in blank the correct term
A linked list is represented by a
pointer to the ......................ode
linked list.
Answer:
of the
arrow_forward
C++ Queue LinkedList, Refer to the codes I've made as a guide and add functions where it can add/insert/remove function to get the output of the program, refer to the image as an example of input & output. Put a comment or explain how the program works/flow.
arrow_forward
Reference-based Linked Lists: Select all of the following statements that are true.
As a singly linked list's node references both its predecessor and its successor, it
is easily possible to traverse such a list in both directions.
According to the terminology introduced in class, the head reference variable in
a singly linked list object references the list's first node.
According to the terminology introduced in class, in a doubly linked list, each
node references both the head and tail node.
In a double-ended singly linked list, the tail reference variable provides access to
the entire list.
In a circular linked list, the last node references the first node.
arrow_forward
struct nodeType {
int infoData;
nodeType * next;
};
nodeType *first;
… and containing the values(see image)
Using a loop to reach the end of the list, write a code segment that deletes all the nodes in the list. Ensure the code performs all memory ‘cleanup’ functions.
arrow_forward
Using Fundamental Data Structures
Purpose: The purpose of this:
Design and develop Applications that incorporate fundamental data structures such as:
Singly Linked Lists
Doubly Linked Lists
Circularly Linked Lists
Exercise 2
If your first name starts with a letter from A-J inclusively:
Use the SinglyLinkedList implementation of the textbook (week 2 lecture examples. Write a method for concatenating two singly linked lists L1 and L2, into a single list L that contains all the nodes of L1 followed by all the nodes of L2. Write a main method to test the new method. Hint: Connect the end of L1 into the beginning of L2.
If your first name starts with a letter from K-Z inclusively:
Use the DoublyLinkedList implementation of the textbook (week 2 lecture examples. Write a method for
concatenating two doubly linked lists L1 and L2, into a single list L that contains all the nodes of L1 followed by all the nodes of L2. Write a main method to test the new method. Hint: Connect the…
arrow_forward
Please help me to finish this code in python
arrow_forward
Create a doubly link list with at least 5 nodes, then perform the following operation on that link list. As you perform the operation, write down the algorithm and c++ code too. Show the operations diagrammatically.
Traversal
Searching
Sorting
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education
Related Questions
- In c++ please explain the code Q1. Given a 'key', delete the first occurrence of this key in the linked list. Iterative Method: To delete a node from the linked list, we need to do the following steps. 1) Find the previous node of the node to be deleted. 2) Change the next of the previous node. 3) Free memory for the node to be deleted.arrow_forwardComplete the code fragment for all three cases Please write python codearrow_forwardkindly don't copy the code from other websites because it's incorrect.. Thanks Linked Lists C Programming : Develop a Student Information System. The system need to implement the insertNode(), deleteNode() and displayList() functions. The insertNode() function is used to insert a new node of student record to the linked list. Assume that the input id is always unique, thus the linked list shall contain the student records with their respective id numbers are in ascending order. The displayList() function is used to display the list after inserting new node and/or after deleting a node. Please refer to the given structure definition shown in Figure 1, Your system interface should consider a few element such as user friendly, attractive and appropriate word. You may add more suitable data in the structure but limited to not more than 3. The deleteNode() function is used to remove a record of the targeted id from the linked list. The deleteNode() function shall return the target id if the…arrow_forward
- TROUBLESHOOT my PYTHON code, please :) The code of a sequential search function is shown on textbook page 60. In fact, if the list is already sorted, the search can halt when the target is less than a given element in the list. For example, given my_list = [2, 5, 7, 9, 14, 27], if the search target is 6, the search can halt when it reaches 7 because it is impossible for 6 to exist after 7. Define a function linearSearchSorted, which is used to search a sorted list. This function displays the position of the target item if found, or 'Target not found' otherwise. It also displays the elements it has visited. To test your function, search for these targets in the list [2, 5, 7, 9, 14, 27]: 2, 6, 14, 27 and 28. Expected output: List: [2, 5, 7, 9, 14, 27] Search target: 2 Elements visited: 2 Target found at position 0 Search target: 6 Elements visited: 2 5 7 Target not found Search target: 14 Elements visited: 2 5 7 9 14 Target found at position 4 Search target: 27 Elements visited: 2…arrow_forwardTOPIC: Big-O Notationarrow_forwardOld MathJax webview Old MathJax webview In Java Some methods of the singly linked list listed below can be implemented efficiently (in different respects) (as opposed to an array or a doubly linked list), others not necessarily which are they and why? b. Implement a function to add an element before the first element. c. Implement a function to add an item after the last one element. d. Implement a function to output an element of the list. e. Implement a function to output the entire list. f. Implement a function to output the number of elements. G. Implement a function to delete an item. H. Implement a function to clear the entire list. I. Implement functionality to search for one or more students by first name, last name, matriculation number or course of study. J. Implement functionality to sort the records of the student, matriculation number and course according to two self-selected sorting methods.arrow_forward
- Python code screenshot and output is mustarrow_forwardPart 2: Advanced Queue (optional) Exercise 1. Priority Queue Based on the above program, create a function void priorityQueue (queue q), which accept current queue and insert new priority queue (int) at the front of the current queue Thus all items in current queue after inserting the new priority item will be moved. Simulate the priority queue by using random Boolean event. Pseudo Code: function priorityQueue (queue q) boolean priority = random Boolean //random Boolean event queue tmp if priority then get front q pop front to tmp while q is not empty get front from q new = front+1 pop from q push new to tmp end while else return q return tmp end functionarrow_forwardLinked List Write a DETAILED algorithm length to count the number of nodes in a singly linked list p, where p points to the first node in the list. The last node has link field NULL. Assume that each node has two fields: data and link. Account for the range of all possible linked list lengths. Needs to be in detailed and code in C PROGRAM would be helpful!arrow_forward
- True/False Select true or false for the statements below. Explain your answers if you like to receive partial credit. 3) Which of the following is true about the insertBeforeCurrent function for a CircularLinked List (CLL) like you did in programming exercise 1?a. If the CLL is empty, you need to create the new node, set it to current, andhave its next pointer refer to itselfb. The worst case performance of the function is O(n)c. If you insert a new element with the same data value as the current node, theperformance improves to O(log n)arrow_forwardStudent should be able to develop the programs for queue using arrays and linked list By Using C++ software. Exercise 1: Implementation of Queue using Array or Linked list Consider a real life situation. Formulate a question and then design a simulation that can help to answer it. Choose one of the following situations: • Cars lined up at a car wash • Customers at a grocery store check-out • Airplanes taking off and landing on a runway • A bank teller Be sure to state any assumptions that you make and provide any probabilistic data that must be considered as part of the scenario.arrow_forward2-) In a double linked list, the structure of a node is defined as follows: struct node { int employeeNo; char name[20]; struct node *next; structnode *prev; }node; the nodes in the list are sorted according to employeeNo in ascending order (from smaller to larger ). Write a function to insert a node with a given name and employeeNo into the list so that the list will remain the sorted. employeeNo değerine göre kiüçükten büyüğe sıralanmış bir çift bağlı liste olsun. Verilen bir isim ve employeeNo değerine sahip düğümü listeye sıra bozulmayacak şekilde ekleyen bir fonksyion yazınız.arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education