Question

a Java code Complete the provided code by adding a method named sum() to the LinkedList...

a Java code

Complete the provided code by adding a method named sum() to the LinkedList class. The sum() method should calculate the sum of all of the positive numbers stored in the linked list.

The input format is the number of items in the list, followed by each of the items, all separated by spaces. Construction of the linked list is provided in the template below. The output should print the sum of the positive values in the list.

For example, the input

4 5 9 -3 2

will produce the output

The sum of the positive items in the list is: 16

(because 5 + 9 + 2 = 16).

import java.util.*;

/***************************************************
* COMP 2140 Lab 4
*
* Simple linked list:
* Add up the positive values stored in a linked list.
***************************************************/

public class Lab4 {

public static void main( String[] args ) {
       Scanner keyboard;
       int listSize;
       LinkedList myList;

       keyboard = new Scanner( System.in );

       //get number of values in list
listSize = keyboard.nextInt();

       //create list
       myList = new LinkedList();

       //fill list
       for (int i=0; i<listSize; i++){
myList.insert(keyboard.nextInt());
       }

       keyboard.close();

       //print results
       System.out.println( "The sum of the positive items in the list is: " + myList.sum() );

} // end main

} // end class Lab4

//=====================================================
// LinkedList class
//
// An ordinary linked list containing ints.
// The list consists of just a pointer (top)
// to the first node in the list.
//=====================================================
class LinkedList {

//================================================
// Node class
//
// A node in the linked list.
// Note that it is inside the LinkedList class.
//
// The usual accessors and mutators (getters and
// setters) are unnecessary. You can directly access
// the instance members "item" and "next" in any
// node that you have a pointer to without using
// accessors or mutators anywhere in the
// LinkedList class. Why? Because item and next
// are declared public in the private Node class
// inside the LinkedList class.
//================================================
private class Node {
       public int item;
       public Node next;

       // Node constructor
       public Node( int newItem, Node newNext ) {
       item = newItem;
       next = newNext;
       }

} // end class Node

/********* Returning to class LinkedList ************/

private Node top; // A pointer to the first node in
// the list (when it's not empty)

/******************************************
*
* LinkedList constructor
*
* Creates an empty LinkedList.
*
******************************************/
public LinkedList( ) {
       top = null;
}

/******************************************
*
* insert
*
* It is passed a new value to add to the list.
*
* It inserts a new node containing newItem
* at the front of the list.
*
* It does NOT check for duplicates ---
* duplicate values are allowed.
*
******************************************/
public void insert( int newItem ) {
       top = new Node( newItem, top );
}
  
public int sum(){
if(next != null){
if(item > 0){
int sum += item ;
  
}
  
}
return sum;

}

} // end class LinkedList

0 0
Add a comment Improve this question Transcribed image text
Answer #1

JAVA PROGRAM

import java.util.*;

public class Lab4 {
/***************************************************
* COMP 2140 Lab 4
*
* Simple linked list:
* Add up the positive values stored in a linked list.
***************************************************/
public static void main( String[] args ) {
Scanner keyboard;
int listSize;
LinkedList myList;

keyboard = new Scanner( System.in );

//get number of values in list
listSize = keyboard.nextInt();

//create list
myList = new LinkedList();

//fill list
for (int i=0; i<listSize; i++){
myList.insert(keyboard.nextInt());
}

keyboard.close();

//print results
System.out.println( "The sum of the positive items in the list is: " + myList.sum() );

} // end main

} // end class Lab4

//=====================================================
// LinkedList class
//
// An ordinary linked list containing ints.
// The list consists of just a pointer (top)
// to the first node in the list.
//=====================================================
class LinkedList {
//================================================
// Node class
//
// A node in the linked list.
// Note that it is inside the LinkedList class.
//
// The usual accessors and mutators (getters and
// setters) are unnecessary. You can directly access
// the instance members "item" and "next" in any
// node that you have a pointer to without using
// accessors or mutators anywhere in the
// LinkedList class. Why? Because item and next
// are declared public in the private Node class
// inside the LinkedList class.
//================================================
private class Node {
public int item;
public Node next;

public Node( int newItem, Node newNext ) {
item = newItem;
next = newNext;
}

}// end class Node

/********* Returning to class LinkedList ************/

private Node top; // A pointer to the first node in
// the list (when it's not empty)

/******************************************
*
* LinkedList constructor
*
* Creates an empty LinkedList.
*
******************************************/
public LinkedList( ) {
top = null;
}

/******************************************
*
* insert
*
* It is passed a new value to add to the list.
*
* It inserts a new node containing newItem
* at the front of the list.
*
* It does NOT check for duplicates ---
* duplicate values are allowed.
*
******************************************/
public void insert( int newItem ) {
top = new Node( newItem, top );
}

public int sum(){
int sum=0;
while(top != null){
if(top.item > 0)
sum += top.item;
top=top.next;
}
return sum;
}// end class LinkedList

}

OUTPUT

S S 9 1 2 6 7 8 : 2 The sum of the positive items in the list is: 16

Add a comment
Know the answer?
Add Answer to:
a Java code Complete the provided code by adding a method named sum() to the LinkedList...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Linkedlist implementation in C++ The below code I have written is almost done, I only need...

    Linkedlist implementation in C++ The below code I have written is almost done, I only need help to write the definition for delete_last() functio​n. ​ Language C++ // LinkedList.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <string> #include <iostream> using namespace std; struct Node { int dataItem;//Our link list stores integers Node *next;//this is a Node pointer that will be areference to next node in the list }; class LinkedList { private: Node *first;...

  • P1 is below package p6_linkedList; import java.util.*; public class LinkedList { public Node header; public LinkedList()...

    P1 is below package p6_linkedList; import java.util.*; public class LinkedList { public Node header; public LinkedList() { header = null; } public final Node Search(int key) { Node current = header; while (current != null && current.item != key) { current = current.link; } return current; } public final void Append(int newItem) { Node newNode = new Node(newItem); newNode.link = header; header = newNode; } public final Node Remove() { Node x = header; if (header != null) { header...

  • JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList...

    JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList Class (some methods included). Remember, you will use the LinkedList Class that we developed in class not Java’s LinkedList Class. You will add the following method to the LinkedList Class: printEvenNodes – this is a void method that prints Nodes that have even indices (e.g., 0, 2, 4, etc). Create a LinkedListDemo class. Use a Scanner Class to read in city names and store...

  • Using Java coding, complete the following: This program should implement a LinkedList data structure to handle...

    Using Java coding, complete the following: This program should implement a LinkedList data structure to handle the management of student records. It will need to be able to store any number of students, using a Linked List. LinearNode.java can be used to aid creating this program Student should be a class defined with the following:    • String name    • int year    • A linked list of college classes (college classes are represented using strings)    • An...

  • C++ LinkedList I need the code for copy constructor and assignment operator #include <iostream> #include <string> using namespace std; typedef string ItemType; struct Node {    ItemType va...

    C++ LinkedList I need the code for copy constructor and assignment operator #include <iostream> #include <string> using namespace std; typedef string ItemType; struct Node {    ItemType value;    Node *next; }; class LinkedList { private:    Node *head;    // You may add whatever private data members or private member functions you want to this class.    void printReverseRecursiveHelper(Node *temp) const; public:    // default constructor    LinkedList() : head(nullptr) { }    // copy constructor    LinkedList(const LinkedList& rhs);    // Destroys all the dynamically allocated memory    //...

  • Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to...

    Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to both classes: public void reverseThisList(), This method will reverse the lists. When testing the method: print out the original list, call the new method, then print out the list again ------------------------------------------------------------------------- //ARRAY LIST class: public class ArrayList<E> implements List<E> { /** Array of elements in this List. */ private E[] data; /** Number of elements currently in this List. */ private int size; /**...

  • C++ program, item.cpp implementation. Implementation: You are supposed to write three classes, called Item, Node and In...

    C++ program, item.cpp implementation. Implementation: You are supposed to write three classes, called Item, Node and Inventory respectively Item is a plain data class with item id, name, price and quantity information accompanied by getters and setters Node is a plain linked list node class with Item pointer and next pointer (with getters/setters) Inventory is an inventory database class that provides basic linked list operations, delete load from file / formatted print functionalities. The majority of implementation will be done...

  • When compiling the LinkedList and Iterator class, the following error is being produced: Note: LinkedList.java uses...

    When compiling the LinkedList and Iterator class, the following error is being produced: Note: LinkedList.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. Any suggestions? public class LinkedList<T> {    Node<T> itsFirstNode;    Node<T> itsLastNode;    private int size;    public LinkedList() {        itsFirstNode = null;        itsLastNode = null;          size = 0;    }    public Iterator<T> getIterator() {        return new Iterator(this);    }    // THIS WILL NEED...

  • n JAVA, students will create a linked list structure that will be used to support a...

    n JAVA, students will create a linked list structure that will be used to support a role playing game. The linked list will represent the main character inventory. The setting is a main character archeologist that is traveling around the jungle in search of an ancient tomb. The user can add items in inventory by priority as they travel around (pickup, buy, find), drop items when their bag is full, and use items (eat, spend, use), view their inventory as...

  • CSCI-2467 Lab 11 – Refactor LinkedList Application to use Generics Background The code consists of three...

    CSCI-2467 Lab 11 – Refactor LinkedList Application to use Generics Background The code consists of three files that implement and use a simple linked list. The code was written in early Java-style using the Object class in order to allow the linked list to be a list of objects of any type. While the code works, it is not type-safe. Refactor the code to use Java Generics. You will need to change the Main class to create a linked list...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT