HELP IN JAVA: Create a circular (singly linked list) of ints using the file numb
ID: 3753108 • Letter: H
Question
HELP IN JAVA: Create a circular (singly linked list) of ints using the file numbers.txt.
You are to use SINGLY LINKED NODES and NOT the java Linked List class.
Pass this list to a method that deletes ever node whose item is an EVEN number.
Print the list. You should have only odd numbers remaining.
numbers.txt:
56 4 9 11 40 68 3 -3 55 40 30 100 90
Rubric:
Must be singly linked nodes
method to create initial CIRCULAR list
method to print CIRCULAR list
method to delete even numbers from CIRCULAR LIST
Must use modular code
Explanation / Answer
Given below is the code for the question.
To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i
Please do rate the answer if it was helpful. Thank you
CircularLinkedList.java
-------------
public class CircularLinkedList {
class Node{
private int data;
Node next;
Node(int d, Node nxt){
data = d;
next = nxt;
}
}
private Node head;
public CircularLinkedList(){
head = new Node(0, null); //dummy node
head.next = head;
}
public void add(int n){
Node last = head;
while(last.next != head)
last = last.next;
last.next = new Node(n, head);
}
public boolean isEmpty(){
if(head.next == head)
return true;
else
return false;
}
public void print(){
Node n = head.next;
System.out.print("{");
while(n != head)
{
System.out.print(n.data + " ");
n = n.next;
}
System.out.println("}");
}
public void removeEven(){
Node prev = head;
Node curr = head.next;
while(curr != head){
if(curr.data % 2 == 0) //even?
{
prev.next = curr.next;
}
else
prev = curr;
curr = curr.next;
}
}
}
TestCircularList.java
-----------------
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TestCircularList {
public static void main(String[] args) {
Scanner infile = null;
try {
infile = new Scanner(new File("numbers.txt"));
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
return;
}
CircularLinkedList clist = new CircularLinkedList();
while(infile.hasNextInt())
clist.add(infile.nextInt());
infile.close();
System.out.println("Numbers loaded from file into circular list are ");
clist.print();
clist.removeEven();
System.out.println("Numbers in circular list after even numbers are removed");
clist.print();
}
}
output
-----
Numbers loaded from file into circular list are
{56 4 9 11 40 68 3 -3 55 40 30 100 90 }
Numbers in circular list after even numbers are removed
{9 11 3 -3 55 }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.