Starting Out with Java: From Control Structures through Data Structures (4th Edition) (What's New in Computer Science)
4th Edition
ISBN: 9780134787961
Author: Tony Gaddis, Godfrey Muganda
Publisher: PEARSON
expand_more
expand_more
format_list_bulleted
Concept explainers
Question
Chapter 19, Problem 2PC
Program Plan Intro
Linked List Sorting and Reversing
Program Plan:
For filename: Modified “LinkedList1.java”
- In this class, additionally need to add two methods “sort()” and “reverse()”.
- Define the method “sort()” which is used to sort the elements in the list by alphabetical order.
- Create two variables “current_node” and “index_value” using “Node” class and this variable set to “null”.
- Declare a string variable “temp_value”.
- Check whether list is empty. If the list is empty, then returns nothing.
- Otherwise,
- Check condition using “for” loop. That is the current node will point to first.
- Check the condition using “for” loop that is for index value will point to next node of current node.
- If data in the “current_node” is greater than the data in “index_value”, then swap the data of “current_node” and “index_index”.
- Check the condition using “for” loop that is for index value will point to next node of current node.
- Check condition using “for” loop. That is the current node will point to first.
- Define the method “reverse()” which is used to reverse the elements in the list.
- Create a list “rev_list” and set it to “null”.
- Performs “while” loop. This loop will perform up to the first node equals to “null”.
- Set a reference “ref” to first node.
- Set “first” to next first node.
- Set next node to “rev_list”.
- Set the “rev_list” to reference “ref”.
- Make the list “rev_list” as the new list.
For filename: “LinkedList1Demo.java”:
- Import required package.
- Define “LinkedList1Demo” class.
- Create an instance for “LinkedList1” class, text area, command text field, and result text field.
- Define constructor for “LinkedList1Demo()” class.
- Create instance.
- Create a panel for “Command Result” text field.
- Create a label for command result.
- Place the text area in center of the frame.
- Create a panel and label for “Command” text field.
- Set up the frame.
- Define private class “commandTextListener” that reply to the user entered command.
- Define “actionPerformed” class.
- Read the command from the command text field.
- Create an object for “Scanner” class.
- Read command from user.
- Check the user entered command using “switch” statement.
- If the user entered command is “sort”, then,
-
- Sort the linked list “new_list” by calling the method “sort()”.
- Displays lists in alphabetical order.
- Assign a status message for the “sort” command was finished.
- Displays status message to “Command Result” text field.
- If the user entered command is “reverse”, then
-
- Reverse the linked list “new_list” by calling the method “reverse()”.
- Prints the reversed list.
- Assign a status message for the “reverse” command was finished.
- Displays status message to “Command Result” text field.
- If the user entered command is “add”, then
-
- Check condition. If it is true, then
- Read index and string element from user.
- Add that index and its element to linked list “new_list” by calling the method “add”.
- Otherwise,
- Read string element from user.
- Add string element to the list “new_list” by calling the method “add”.
- Display the added string elements.
- Check condition. If it is true, then
- If the user entered command is “remove”, then
-
- Check condition. If it is true, then
- Read an index from user.
- Remove an element at given index.
- Display the removed element at given index to “Command Result” text field.
- Otherwise,
- Read an element from the list.
- Obtain the Boolean result.
- Convert the Boolean into string.
- Display the Boolean result to “Command Result” text field.
- Displays string elements in the list
- Check condition. If it is true, then
- If the user entered command is “isEmpty”, then
-
- Check the given list is empty or not by calling the method “isEmpty” and store the result in “result_text3”.
- Display the result to “Command Result” text field.
- If the user entered command is “size”, then
-
- Compute the size of list “new_list” by calling the method “size()” and store the result in “result_text4”.
- Display the result to “Command Result” text field.
- Define “actionPerformed” class.
- Define main function.
- The instance of “LinkedList1Demo” class displays its window.
Expert Solution & Answer
Want to see the full answer?
Check out a sample textbook solutionStudents have asked these similar questions
What is the biggest advantage of linked list over array?
Group of answer choices
Unlike array, linked list can dynamically grow and shrink
With linked list, it is faster to access a specific element than with array
Linked list is easier to implement than array
Unlike array, linked list can only hold a fixed number of elements
In python. Write a LinkedList class that has recursive implementations of the add and remove methods. It should also have recursive implementations of the contains, insert, and reverse methods. The reverse method should not change the data value each node holds - it must rearrange the order of the nodes in the linked list (by changing the next value each node holds).
It should have a recursive method named to_plain_list that takes no parameters (unless they have default arguments) and returns a regular Python list that has the same values (from the data attribute of the Node objects), in the same order, as the current state of the linked list.
The head data member of the LinkedList class must be private and have a get method defined (named get_head). It should return the first Node in the list (not the value inside it).
As in the iterative LinkedList in the exploration, the data members of the Node class don't have to be private. The reason for that is because Node is a trivial class…
Implements clone which duplicates a list. Pay attention, because if there are sublists, they must be duplicated as well. Understand the implementation of the following function, which recursively displays the ids of each node in a list
Develop your solution as follows:
First copy the nodes of the current list (self)
Create a new list with the copied nodes
Loop through the nodes of the new list checking the value field
If this field is also a list (use isinstance as in the show_ids function) then it calls clone on that list and substitutes the value.
Complete the code:
def L4(*args,**kwargs): class L4_class(L):
def clone(self):
def clone_node(node): return <... YOUR CODE HERE ...>
r = <... YOUR CODE HERE...> return r return L4_class(*args,**kwargs)
Chapter 19 Solutions
Starting Out with Java: From Control Structures through Data Structures (4th Edition) (What's New in Computer Science)
Ch. 19.1 - Prob. 19.1CPCh. 19.1 - Prob. 19.2CPCh. 19.3 - Prob. 19.4CPCh. 19 - A list is a collection that _____. a. associates...Ch. 19 - Prob. 2MCCh. 19 - Prob. 3MCCh. 19 - Prob. 4MCCh. 19 - Prob. 5MCCh. 19 - Prob. 6MCCh. 19 - Prob. 7MC
Ch. 19 - Prob. 11TFCh. 19 - Prob. 12TFCh. 19 - Prob. 13TFCh. 19 - Prob. 14TFCh. 19 - Prob. 15TFCh. 19 - Prob. 16TFCh. 19 - Prob. 17TFCh. 19 - Prob. 18TFCh. 19 - Prob. 19TFCh. 19 - Prob. 20TFCh. 19 - Prob. 1FTECh. 19 - Prob. 2FTECh. 19 - Prob. 3FTECh. 19 - Prob. 4FTECh. 19 - Prob. 5FTECh. 19 - Prob. 1AWCh. 19 - Prob. 2AWCh. 19 - Prob. 3AWCh. 19 - Prob. 4AWCh. 19 - Prob. 3SACh. 19 - Prob. 4SACh. 19 - Prob. 5SACh. 19 - Consult the online Java documentation and...Ch. 19 - Prob. 1PCCh. 19 - Prob. 2PC
Knowledge Booster
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.Similar questions
- Part2: LinkedList implementation 1. Create a linked list of type String Not Object and name it as StudentName. 2. Add the following values to linked list above Jack Omar Jason. 3. Use addFirst to add the student Mary. 4. Use addLast to add the student Emily. 5. Print linked list using System.out.println(). 6. Print the size of the linked list. 7. Use removeLast. 8. Print the linked list using for loop for (String anobject: StudentName){…..} 9. Print the linked list using Iterator class. 10. Does linked list hava capacity function? 11. Create another linked list of type String Not Object and name it as TransferStudent. 12. Add the following values to TransferStudent linked list Sara Walter. 13. Add the content of linked list TransferStudent to the end of the linked list StudentName 14. Print StudentName. 15. Print TransferStudent. 16. What is the shortcoming of using Linked List?arrow_forwardread carefully please Without using the java collections interface (i.e. do not import java.util.List, LinkedList, etc. ) I need to write a java program that inserts a new String element (String newItem) into a linked list after another specified item (String itemToInsertAfter). For example if items "A", "B", "C" and "D" are in a linked list in that order and the below method is called, insertAfter("E", "C"), then "E" would be inserted after "C", making the final list to be "A", "B", "C", "E" and "D" with no nulls or blank elements or any elements missing or anything. It should work for all lenghths of linkedlists of Strings. I am not sure how to do this simple problem, can you help? public Boolean insertAfter(String newItem, String itemToInsertAfter) { // returns true if done successfully, else returns false if itemToInsertAfter cannot be found or some other error }arrow_forward(Implement a doubly linked list) The MyLinkedList class used in Listing 24.6 is a one-way directional linked list that enables one-way traversal of the list. Modify the Node class to add the new data field name previous to refer to the previous node in the list, as follows:public class Node<E> { E element; Node<E> next; Node<E> previous;public Node(E e) { element = e; } }Implement a new class named TwoWayLinkedList that uses a doubly linked list to store elements. The MyLinkedList class in the text extends MyAbstractList. Define TwoWayLinkedList to extend the java.util.AbstractSequentialList class. You need to implement all the methods defined in MyLinkedList as well as the methods listIterator() and listIterator(int index). Both return an instance of java.util. ListIterator<E>. The former sets the cursor to the head of the list and the latter to the element at the specified index.arrow_forward
- Question 20 A list is a collection with additional index- and iteration- related operations. True False Question 21 O(N) is the order of growth execution time of the size operation when using the SortedArrayCollection class, assuming a collection size of N. True False Question 22 If N represents the number of elements in the list, then the index-based set method of the ABList class is O(1). True False Question 23 O(N) is the order of growth execution time of the remove operation when using the LinkedCollection class, assuming a collection size of N. True False Question 24 It is not possible to use an array to implement a linked list. True False Question 25 O(N) is the order of growth execution time of the remove operation when using the ArrayCollection class, assuming a collection size of N. True False Question 26 Our linked implementation of lists implements a bounded list. True False Question 27 O(N) is the order of growth execution time of the contains operation…arrow_forwardIn this task, a skip list data structure should be implemented. You can follow the followinginstructions:- Implement the class NodeSkipList with two components, namely key node and arrayof successors. You can also add a constructor, but you do not need to add anymethod.- In the class SkipList implement a constructor SkipList(long maxNodes). The parameter maxNodes determines the maximal number of nodes that can be added to askip list. Using this parameter we can determine the maximal height of a node, thatis, the maximal length of the array of successors. As the maximal height of a nodeit is usually taken the logarithm of the parameter. Further, it is useful to constructboth sentinels of maximal height.- In the class SkipList it is useful to write a method which simulates coin flip andreturns the number of all tosses until the first head comes up. This number representsthe height of a node to be inserted.- In the class SkipList implement the following methods:(i) insert, which accepts…arrow_forwardAdd a new public member function to the LinkedList class named reverse() which reverses the items in the list. You must take advantage of the doubly-linked list structure to do this efficiently as discussed in the videos/pdfs, i.e. swap each node’s prev/next pointers, and finally swap headPtr/tailPtr. Demonstrate your function works by creating a sample list of a few entries in main(), printing out the contents of the list, reversing the list, and then printing out the contents of the list again to show that the list has been reversed. Note: your function must actually reverse the items in the doubly-linked list, not just print them out in reverse order! Note: we won't use the copy constructor in this assignment, and as such you aren't required to update the copy constructor to work with a doubly-linked list. This is what I have so far but its not working! template<class ItemType>void LinkedList<ItemType>::reverse(){ Node<ItemType>*curPtr,*prev,*next;…arrow_forward
- Code Restructuring: Methods for Linked List operations are given. Restructure the codes to improve performance of codes. Linked List is a part of the Collection framework present in java.util package, however, to be able to check the complexity of Linked List operations, we can recode the data structure based on Java Documentation https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html Instruction 1: Two (2) Java classes are provided, first, the Linked List class and second, the Linked List interface. On the Linked List class, check the comments, analyze then try to recode the said method/s. Post the changes in your code, if any. package com.linkedlist; public class LinkedList<E> implements ListI<E>{ //The Node Object signatures and constructor class Node<E>{ E data; Node<E> next; public Node(E obj) { data=obj; next=null; } }…arrow_forwardUSING C++ Find and delete the node with the smallest info in the list. (Delete only the first occurrence and traverse the list only once.) Add these as abstract functions in the class linkedListType and provide the definitions of these functions in the class unorderedLinkedList. Also, write a program to test these functions. PLS USE THIS CLASS TYPESarrow_forwardWithout using the java collections interface (i.e. do not import java.util.List, LinkedList, etc. ) Write a java program that inserts a new String element (String newItem) into a linked list before another specified item (String itemToInsertBefore). For example if items "A", "B", "C" and "D" are in a linked list in that order and the below method is called, insertBefore("E", "C"), then "E" would be inserted before "C", making the final list to be "A", "B", "E", "C" and "D" with no nulls or blank elements or any elements missing or anything. It should work for all lenghths of linkedlists of Strings. public Boolean insertBefore(String newItem, String itemToInsertBefore) { // returns true if done successfully, else returns false if itemToInsertBefore cannot be found or some other error }arrow_forward
- java program java method: Write a method replace to be included in the class KWLinkedList (for doubly linked list) that accepts two parameters, searchItem and repItem of type E. The method searches for searchItem in the doubly linked list, if found then replace it with repItem and return true. If the searchItem is not found in the doubly linked list, then insert repItem at the end of the linked list and return false. Assume that the list is not empty. You can use ListIterator and its methods to search the searchItem in the list and replace it with repItem if found. Do not call any method of class KWLinkedList to add a new node at the end of the list. Method Heading: public boolean replace(E searchItem, E repItem) Example: searchItem: 15 repItem: 17 List (before method call): 9 10 15 20 4 5 6 List (after method call) : 9 10 17 20 4 5 6arrow_forwardWrite a Python code using the given function and conditions. Do not use Numpy. Use LinkedList Manipulation. Given function: def insert(self, newElement, index) Pre-condition: The list is not empty. Post-condition: This method inserts newElement at the given index of the list. If an element with the same key as newElement value already exists in the list, then it concludes the key already exists and does not insert the key. [You must also check the validity of the index].arrow_forwardImplement a simple linked list in Python (Write source code and show output) with basic linked list operations like: (a) create a sequence of nodes and construct a linear linked list. (b) insert a new node in the linked list. (b) delete a particular node in the linked list. (c) modify the linear linked list into a circular linked list. Use this template: class Node:def __init__(self, val=None):self.val = valself.next = Noneclass LinkedList:"""TODO: Remove the "pass" statements and implement each methodAdd any methods if necessaryDON'T use a builtin list to keep all your nodes."""def __init__(self):self.head = None # The head of your list, don't change its name. It shouldbe "None" when the list is empty.def append(self, num): # append num to the tail of the listpassdef insert(self, index, num): # insert num into the given indexpassdef delete(self, index): # remove the node at the given index and return the deleted value as an integerpassdef circularize(self): # Make your list circular.…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