The following program creates a linked list which contains 5 links. Add a method called doubleValue() to the LinkedList class. The doubleValue() method must double the value of the number data field in each link. Add the required code to the main() method to call the doubleValue() method and display the revised list.
public class Link {
private int number;
private Link next;
public Link(int x)
{
number = x;
}
public void displayLink()
{
System.out.println("The number is: " + number);
}
public int getNumber()
{
return number;
}
public void setNumber(int y)
{
number =y;
}
public Link getNext()
{
return next;
}
public void setNext(Link l)
{
next=l;
}
}
public class LinkedList {
private static int size=0;
private Link first;
public LinkedList()
{
first = null;
}
public boolean isEmpty()
{
return (first==null);
}
public void insertFirst(int x)//insert at first
{
Link newLink = new Link(x);
newLink.setNext(first);
first = newLink;
size++;
}
public void deleteFirst()
{
first = first.getNext();
size--;
}
public void displayList()
{
System.out.println("List (first-->last): ");
Link current = first;
while(current != null)
{
current.displayLink();
current = current.getNext();
}
}
public Link find(int key)
{
Link current = first;
while(current.getNumber() != key)
{
if(current.getNext() == null)
{
return null;
}
else
{
current = current.getNext();
}
}
return current;
}
public int size()
{
return size;
}
}
public class TestLinkedList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertFirst(2);
list.insertFirst(4);
list.insertFirst(6);
list.insertFirst(8);
list.insertFirst(10);
list.displayList();
}
}
The output must look like the following:
List (first-->last):
The number is: 10
The number is: 8
The number is: 6
The number is: 4
The number is: 2
List (first-->last):
The number is: 20
The number is: 16
The number is: 12
The number is: 8
The number is: 4
If you have any problem with the code feel free to comment.
doubleValue()
public void doubleValue() {
//getting the first link address
Link current = first;
//looping through the list till there is no next value
while (current != null) {
//getteing the number and setting double its value
current.setNumber(current.getNumber()*2);
//pointing to next link
current = current.getNext();
}
}
Test Class
public class Test {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertFirst(2);
list.insertFirst(4);
list.insertFirst(6);
list.insertFirst(8);
list.insertFirst(10);
list.displayList();
list.doubleValue();
list.displayList();
}
}
Output
Get Answers For Free
Most questions answered within 1 hours.