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 1PC
Program Plan Intro
Generic Linked Lists
Program Plan:
- Import required package.
- Define “GenericLinkedList” class.
- Define “Node” class.
- Declare a value of a list element in generic type.
- Declare next node in the list using “Node” class.
- Parameterized constructor for “Node” class with two parameters.
- Parameterized constructor for “Node” class with one parameter.
- Declare variable for head of the list.
- Declare variable for last element of list.
- Define the method “clear()” which is used to remove all elements from the list.
- Initializes the index to “0”.
- If the head of the list is not “null”, then set temp node to head of the list and performs “while” loop.
- Remove an element in the list one by one using “while” loop.
- Set “temp_node” to next value of “temp_node”.
- Remove the given element by calling the method “remove”.
- Remove an element in the list one by one using “while” loop.
- Define the method “get()” which is used to return the value at given index in the list.
- Initializes “idx” to “0”.
- If the head of the list is not null, then
- Set head of list to “tempValue”.
- Check condition using “while” loop.
- If “idx” equals to given “index”, then return the element at given position.
- Otherwise, increment the value of “idx” and set “tempValue” to next value of “tempValue”
- Define the method “set()” which is used to replace the value at the specified position with the specified element and also return the previous element.
- Initializes “idx” to “0”.
- Check condition using “while” loop.
- If “idx” equals to given “index”, then replace the element at given position and return the previous element.
- Otherwise, increment the value of “idx” and set “tempValue” to next value of “tempValue”.
- Define the method “isEmpty()” which is used to compute whether list is in empty or not.
- Define the method “size()” which is used to compute the size of list.
- Define the method “add()” which is used to add an element to the list.
- Define the method “remove” which is used to remove an element from the list.
- Define main function.
- Create object for “Scanner” class.
- Create object “list” in “double” type using “GenericLinkedList” class.
- Add elements to “list” using “add()” method.
- Display the elements in list.
- To test the “set” method.
- Initializes the index to “-1”.
- Declare variable in “double” type.
- Performs “do-while” loop.
- Read index string from user.
- Convert the string value in integer.
- If the user entered index is less than “0” or greater than or equal to “size”, then display an error message.
- Read the new element for given index.
- Convert the string to double.
- Replace the new element in the place of old element by calling the method “set”.
- Display the old element in the given index.
- Display the list after calling “set” method.
-
- To test the “get” method.
- Initializes the index to “-1”.
- Performs “do-while” loop.
- Read the index from user.
- Convert the string to integer.
- If the user entered index is less than “0” or greater than or equal to “size”, then display an error message
- Display the element at given index by calling the method “get()”.
- Clear all the elements in the list by calling the method “clear()”.
- Display the size of list after clearing the list by calling “size()” method.
- To test the “get” method.
-
- Define “Node” class.
Expert Solution & Answer
Want to see the full answer?
Check out a sample textbook solutionStudents have asked these 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?
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 6
Hello. Please add a toString() function to the Java class implementation of the singly-linked list which returns the contents of the singly-linked list. Also, does Java have a built-in class that implements singly-linked lists? Thank you.
public class SinglyLinkedList<E>{ private static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { return element;} public Node<E> getNext() { return next;} public void setNext(Node<E> n) { next = n;} } private Node<E> head = null; private Node<E> tail = null; private int size = 0; public SinglyLinkedList() {} public int size() { return size;} public boolean isEmpty() { return size == 0;} public E first() { if(isEmpty()) return null; return head.getElement(); } public E last() {…
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
- Implement class “LinkedList” which has two private data members head: A pointer to the Node class length: length of the linked list // Node* GetNode(int index) const;A private function which is only accessible to the class methods. This function takes an array-like index and returns the address of the node at that index. For example, index 0 corresponds to the head and index length-1 corresponds to end node of the linked list. The function returns NULL if the index is out of bound.// Implement the following public method: 1. bool RemoveHead();// Use RemoveAt FunctionRemove first node. Return true if successful, otherwise, false.2. bool RemoveEnd();// Use RemoveAt FunctionRemove last node. Return true if successful, otherwise, false.3 . void DisplayList() const;Display data of the whole linked list this in c++.arrow_forwardWrite a Java class myLinkedList to simulate a singly linked list using arrays as the underlying structure. Include the following methods: 1. insert an element within the linked list.(this should also work for the front and the rear of the list) 2. Remove an element from the linked list 3. Display (print) the elements of the linked list in order. 4. A method to check if the list is "empty". Test your solution using a linked list that initially has the characters A, B, D, E, F, and G. Insert "C" between B and D. Remove element "F". [Hint: One solution (recommended) is to use 2 arrays. One for the data, and the other for the "next" pointer. Also, consider using dummy nodes for the front, and possibly the rear of the list] Extend the solution so that it simulates a doubly linked list! (hint: You will need a third array to represent the "backward" pointers)arrow_forwardimplement this method: numOccurrencesRec(LNode node, int n, int key) – This method takes as parameters a reference to the head of a linked list, a position specified by n, and a key. It returns the number of occurrences of the key in the linked list beginning at the n-th node. If n = 0, it means you should search in the entire linked list. If n = 1, then you should skip the first node in the list.arrow_forward
- Consider the following implementation of the node and doubly linked-list: Extend the class doubly_linked_list by adding the following methods: *Largest method .This method should return the largest element in a doubly linked-list. *Delete method. This method should delete the first occurrence of an element (value) from a doubly linked-list. USE C++ PLEASE THE CODE : template <class type> class node{public:type info;node<type> * next;// nextnode<type> * prev;//back }; template <class type>class doubly_linked_list {//data membersprivate:node<type> *head, *tail;int length;public:doubly_linked_list(){head = tail = NULL;length = 0;}bool isEmpty(){ // return (head==NULL);if (head == NULL)return true;elsereturn false;} void Append(type e){node<type> *newnode = new node<type>;newnode->info = e;if (isEmpty()){newnode->next = NULL;newnode->prev = NULL;head = newnode;tail = newnode;}else{tail->next = newnode;newnode->prev =…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_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
- The following method is defined within a linked list class. What does it do? void MyList::doSomething() { Node* p = head; while (p) { cout << p->value << " "; p = p->next; }} Group of answer choices inserts a node into linked list deletes a node from linked list displays contents of linked list destroys the entire linked listarrow_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_forwardIn 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…arrow_forward
- Implement class “LinkedList” which has two private data members head: A pointer to the Node class length: length of the linked listImplement the following private method:1. Node* GetNode(int index) const;A private function which is only accessible to the class methods. . For example, index 0 corresponds to the head and index length-1 corresponds to end node of the linked list. The function returns NULL if the index is out of bound.Implement the following public methods:2. LinkedList();Constructor that sets head to NULL and length equal to zero.3. bool InsertAt(int data, int index);Insert a new node at the index. Return true if successful, otherwise,return false. The new node should be at the position “index” in the linked list after inserting it. You might have to use GetNode private function. these 3 partsarrow_forwardLinked list. Complete the function that takes as a parameter the head of a linked list and prints the linked list in reverse order. If the linked list had the contents: of,the,and,on,a,an,ok. Then the correct output would be: ok,an,a,on,and,the,of. Given: struct node { char word[31]; struct node *prev, next; }; void print_reverse(struct node *head) { }arrow_forwardTRUE or FALSE? Answer the following question and state the reason why: The delete operation only involves the removing of the node from the list without breaking the links created by the next node. You need an array to represent each node in a linked list. STL lists are also efficient at adding elements at their back because they have a built-in pointer to the last element in the list. A circular linked list has 2 node pointers. cout<<list.back()<<endl; = The back member function returns a reference to the last element in the list. In a Dynamic Stack, the pointer top stays at the head after a push operation. During a Pop operation in Static Stack, the elements are being moved one step up. In a dynamic implementation of stack, the pointer top has an initial value of null. In a dynamic stack, the node that was popped is deleted. In a dynamic stack, the pointer top stays at the head after push operation. STL function top returns a reference to element at the top of the…arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- C++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage Learning
C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning