Lab 7: Linked Lists

advertisement
CPE 102
Lab 7: Linked Lists
created by Dr. Hasmik Gharibyan
Part 1: Linked list of integers
a) Define a LList class to represent a linked list of integers.
The class has one private instance variable head of Node type.
LList has one constructor – to create an empty list.
LList has a nested private class Node with two public instance variables – one for the list element
(int type value), and second for the link (Node type next).
LList has the following methods:
- addToFront: the int item given as a parameter is added to the front of the linked list.
- search: returns a boolean value – true, if the int item given as a parameter is found in the
list, and false otherwise.
- sum: returns an int value – the sum of all elements of the list.
- listLength: returns an integer – the number of elements in the list.
- max: returns an integer – the greatest element in the list. If the list is empty, returns
Integer.MIN_VALUE (this is a static constant in Integer class representing the smallest
integer number).
- min: returns an integer – the smallest element in the list. If the list is empty, returns
Integer.MAX_VALUE (this is a static constant in Integer class representing the largest
integer number).
- toString: returns a string containing all elements of the list separated by spaces
Note: all methods except add and search do not have parameters.
Edit and compile LinkList class.
b) Define an application class LListDriver.
This class has only one method – main, where you
- define a LList object list (initially it will be an empty list, since that is what the only
constructor defined in the class will do).
- Prompt the user to enter 10 integers. Then, with a for-loop read in 10 integers from the
keyboard and add to the list.
- Prompt the user for an integer to be searched in the list and output a message, to inform
the user how the search was performed.
- Output a message for the user giving the sum of the elements in the list .
- Output a message for the user giving the greatest element of the list.
- Output a message for the user giving the smallest element of the list.
- Output a message for the user giving the number of elements in the list.
- Output the list itself.
Attention: 1. Make sure each output sentence goes on a separate line.
2. Don’t prompt the user 10 times for ten integers, give only one prompt, asking to
input 10 numbers.
3. Don’t worry about any exceptions or errors.
Edit, compile and execute this program. Turn-in the hard copy of the files, if asked.
1
Download