SlideShare a Scribd company logo
1 of 7
Download to read offline
-JAVA-
provide a test class that do the required
-you may add methods you need in the SLL-
//************************** SLL.java *********************************
// a generic singly linked list class
public class SLL{
private class SLLNode {
private T info;
private SLLNode next;
public SLLNode() {
this(null,null);
}
public SLLNode(T el) {
this(el,null);
}
public SLLNode(T el, SLLNode ptr) {
info = el; next = ptr;
}
}
protected SLLNode head, tail;
public SLL() {
head = tail = null;
}
public boolean isEmpty() {
return head == null;
}
public void addToHead(T el) {
head = new SLLNode(el,head);
if (tail == null)
tail = head;
}
public void addToTail(T el) {
if (!isEmpty()) {
tail.next = new SLLNode(el);
tail = tail.next;
}
else head = tail = new SLLNode(el);
}
public T deleteFromHead() { // delete the head and return its info;
if (isEmpty())
return null;
T el = head.info;
if (head == tail) // if only one node on the list;
head = tail = null;
else head = head.next;
return el;
}
public T deleteFromTail() { // delete the tail and return its info;
if (isEmpty())
return null;
T el = tail.info;
if (head == tail) // if only one node in the list;
head = tail = null;
else { // if more than one node in the list,
SLLNode tmp; // find the predecessor of tail;
for (tmp = head; tmp.next != tail; tmp = tmp.next);
tail = tmp; // the predecessor of tail becomes tail;
tail.next = null;
}
return el;
}
public void delete(T el) { // delete the node with an element el;
if (!isEmpty())
if (head == tail && el.equals(head.info)) // if only one
head = tail = null; // node on the list;
else if (el.equals(head.info)) // if more than one node on the list;
head = head.next; // and el is in the head node;
else { // if more than one node in the list
SLLNode pred, tmp;// and el is in a nonhead node;
for (pred = head, tmp = head.next;
tmp != null && !tmp.info.equals(el);
pred = pred.next, tmp = tmp.next);
if (tmp != null) { // if el was found;
pred.next = tmp.next;
if (tmp == tail) // if el is in the last node;
tail = pred;
}
}
}
@Override
public String toString() {
if(head == null)
return "[ ]";
String str = "[ ";
SLLNode tmp = head;
while(tmp != null){
str += tmp.info + " ";
tmp = tmp.next;
}
return str+"]";
}
public boolean contains(T el) {
if(head == null)
return false;
SLLNode tmp = head;
while(tmp != null){
if(tmp.info.equals(el))
return true;
tmp = tmp.next;
}
return false;
}
public int size(){
if(head == null)
return 0;
int count = 0;
SLLNode p = head;
while(p != null) {
count++;
p = p.next;
}
return count;
}
//
// Please write the methods of Task02 here:
//
public void insertBefore(int index, T newElem) throws Exception {
//throws exception if the list is empty
if(isEmpty()){
throw new Exception("list is empty");
}
//inserts
if(index < size()){
if (index == 0){
SLLNode newnode = new SLLNode<>(newElem, head);
head = newnode;
}
else{
SLLNode temp = head;
SLLNode newnode = new SLLNode<>(newElem, null);
for (int i = 0; i < index - 1; i++) {
temp = temp.next;
}
newnode.next = temp.next;
temp.next = newnode;
}
}
//throws exception for invalid index
else {
throw new Exception("index is not valid");
}
}
public T delete(int index) throws Exception{
//throws exception if the list is empty
if (isEmpty()) {
throw new Exception("list is empty");
}
//removes
if (index < size()) {
if (index == 0) {
return deleteFromHead();
}
else if (index == size() - 1) {
return deleteFromTail();
}
SLLNode temp = head;
for (int i = 0; i < index - 1; i++) {
temp = temp.next;
}
T elm = temp.next.info;
temp.next = temp.next.next;
return elm;
}
//invalid index
throw new Exception("index is not valid");
}
public void insertAfterSecondOccurrence(T e1, T e2) throws Exception {
//throws exception if the list is empty
if (isEmpty()) {
throw new Exception("list is empty");
}
//inserts
int pos = -1;
int counter = 0;
SLLNode temp = head;
for (int i = 0; i < size(); i++) {
if (temp.info == e2) {
counter++;
}
if (counter == 2) {
pos = i;
break;
}
temp = temp.next;
}
if (pos != -1) {
if (pos + 1 == size()) {
addToTail(e1);
} else {
insertBefore(pos + 1, e1);
}
}
//the list has no second occurrence of e2
if (pos == -1){
throw new Exception("list has no second occurrence of " + e2);
}
}
} Part I: Programming (50 points) Use the singly linked list class introduced in the lab to
implement integers of unlimited size. Each node of the list should store one digit of the integer.
You are to implement the addition, subtraction and multiplication operations. Please note that
any additional data structure to be used in solving this problem has to be taken from the ones
introduced in the ICS 202 lab. In addition, provide a test class that will do the following: It will
keep asking the user to enter two integers, choose one of the operations (addition, subtraction,
multiplication) and then display the result. The program will stop upon entering the "#"
character (without the double quotes).

More Related Content

Similar to -JAVA-provide a test class that do the required -you may add met.pdf

Please finish the int LLInsert function.typedef struct STUDENT {.pdf
Please finish the int LLInsert function.typedef struct STUDENT {.pdfPlease finish the int LLInsert function.typedef struct STUDENT {.pdf
Please finish the int LLInsert function.typedef struct STUDENT {.pdf
fortmdu
 
I need to fill-in TODOs in .cpp file and in .h file Could some.pdf
I need to fill-in TODOs in .cpp file and in .h file Could some.pdfI need to fill-in TODOs in .cpp file and in .h file Could some.pdf
I need to fill-in TODOs in .cpp file and in .h file Could some.pdf
forladies
 
mainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdfmainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdf
fathimafancyjeweller
 
please help me in C++Objective Create a singly linked list of num.pdf
please help me in C++Objective Create a singly linked list of num.pdfplease help me in C++Objective Create a singly linked list of num.pdf
please help me in C++Objective Create a singly linked list of num.pdf
aminbijal86
 
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdfimport java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
Stewart29UReesa
 
#include sstream #include linkylist.h #include iostream.pdf
#include sstream #include linkylist.h #include iostream.pdf#include sstream #include linkylist.h #include iostream.pdf
#include sstream #include linkylist.h #include iostream.pdf
aravlitraders2012
 
SOURCE CODEimport java.util.Iterator;public class CircularLinke.pdf
SOURCE CODEimport java.util.Iterator;public class CircularLinke.pdfSOURCE CODEimport java.util.Iterator;public class CircularLinke.pdf
SOURCE CODEimport java.util.Iterator;public class CircularLinke.pdf
arccreation001
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
rohit219406
 
I keep getting NullPointerExcepetion, can someone help me with spinL.pdf
I keep getting NullPointerExcepetion, can someone help me with spinL.pdfI keep getting NullPointerExcepetion, can someone help me with spinL.pdf
I keep getting NullPointerExcepetion, can someone help me with spinL.pdf
arkmuzikllc
 
#includeiostream struct node {    char value;    struct no.pdf
#includeiostream struct node {    char value;    struct no.pdf#includeiostream struct node {    char value;    struct no.pdf
#includeiostream struct node {    char value;    struct no.pdf
ankitmobileshop235
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdf
malavshah9013
 
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdfProblem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
JamesPXNNewmanp
 

Similar to -JAVA-provide a test class that do the required -you may add met.pdf (20)

Please finish the int LLInsert function.typedef struct STUDENT {.pdf
Please finish the int LLInsert function.typedef struct STUDENT {.pdfPlease finish the int LLInsert function.typedef struct STUDENT {.pdf
Please finish the int LLInsert function.typedef struct STUDENT {.pdf
 
I need to fill-in TODOs in .cpp file and in .h file Could some.pdf
I need to fill-in TODOs in .cpp file and in .h file Could some.pdfI need to fill-in TODOs in .cpp file and in .h file Could some.pdf
I need to fill-in TODOs in .cpp file and in .h file Could some.pdf
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
 
mainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdfmainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdf
 
please help me in C++Objective Create a singly linked list of num.pdf
please help me in C++Objective Create a singly linked list of num.pdfplease help me in C++Objective Create a singly linked list of num.pdf
please help me in C++Objective Create a singly linked list of num.pdf
 
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdfimport java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
 
#include sstream #include linkylist.h #include iostream.pdf
#include sstream #include linkylist.h #include iostream.pdf#include sstream #include linkylist.h #include iostream.pdf
#include sstream #include linkylist.h #include iostream.pdf
 
Linked lists
Linked listsLinked lists
Linked lists
 
Tugas1
Tugas1Tugas1
Tugas1
 
SOURCE CODEimport java.util.Iterator;public class CircularLinke.pdf
SOURCE CODEimport java.util.Iterator;public class CircularLinke.pdfSOURCE CODEimport java.util.Iterator;public class CircularLinke.pdf
SOURCE CODEimport java.util.Iterator;public class CircularLinke.pdf
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
 
I keep getting NullPointerExcepetion, can someone help me with spinL.pdf
I keep getting NullPointerExcepetion, can someone help me with spinL.pdfI keep getting NullPointerExcepetion, can someone help me with spinL.pdf
I keep getting NullPointerExcepetion, can someone help me with spinL.pdf
 
#includeiostream struct node {    char value;    struct no.pdf
#includeiostream struct node {    char value;    struct no.pdf#includeiostream struct node {    char value;    struct no.pdf
#includeiostream struct node {    char value;    struct no.pdf
 
137 Lab-2.2.pdf
137 Lab-2.2.pdf137 Lab-2.2.pdf
137 Lab-2.2.pdf
 
DSA(1).pptx
DSA(1).pptxDSA(1).pptx
DSA(1).pptx
 
Linked Stack program.docx
Linked Stack program.docxLinked Stack program.docx
Linked Stack program.docx
 
Ll.pptx
Ll.pptxLl.pptx
Ll.pptx
 
linked list.pptx
linked list.pptxlinked list.pptx
linked list.pptx
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdf
 
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdfProblem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
 

More from alphawheels007

1) Las especies con tiempos de generaci�n m�s largos deben tener .pdf
1) Las especies con tiempos de generaci�n m�s largos deben tener .pdf1) Las especies con tiempos de generaci�n m�s largos deben tener .pdf
1) Las especies con tiempos de generaci�n m�s largos deben tener .pdf
alphawheels007
 
1) En una poblaci�n que est� en equilibrio de Hardy-Weinberg, hay do.pdf
1) En una poblaci�n que est� en equilibrio de Hardy-Weinberg, hay do.pdf1) En una poblaci�n que est� en equilibrio de Hardy-Weinberg, hay do.pdf
1) En una poblaci�n que est� en equilibrio de Hardy-Weinberg, hay do.pdf
alphawheels007
 

More from alphawheels007 (20)

1) �Cu�l de las AD es falsa con respecto a las infecciones por virus.pdf
1) �Cu�l de las AD es falsa con respecto a las infecciones por virus.pdf1) �Cu�l de las AD es falsa con respecto a las infecciones por virus.pdf
1) �Cu�l de las AD es falsa con respecto a las infecciones por virus.pdf
 
1) La selecci�n sexual elige el fenotipo que le dar� a la descendenc.pdf
1) La selecci�n sexual elige el fenotipo que le dar� a la descendenc.pdf1) La selecci�n sexual elige el fenotipo que le dar� a la descendenc.pdf
1) La selecci�n sexual elige el fenotipo que le dar� a la descendenc.pdf
 
1) Which of the following terms is not associated with price discrim.pdf
1) Which of the following terms is not associated with price discrim.pdf1) Which of the following terms is not associated with price discrim.pdf
1) Which of the following terms is not associated with price discrim.pdf
 
1) What is the role of the senior leaders in the hospital How shoul.pdf
1) What is the role of the senior leaders in the hospital How shoul.pdf1) What is the role of the senior leaders in the hospital How shoul.pdf
1) What is the role of the senior leaders in the hospital How shoul.pdf
 
1) What percentage of all sampled fish have a flattened body shape A.pdf
1) What percentage of all sampled fish have a flattened body shape A.pdf1) What percentage of all sampled fish have a flattened body shape A.pdf
1) What percentage of all sampled fish have a flattened body shape A.pdf
 
1) Use Link State algorithm to determine the shortest path from node.pdf
1) Use Link State algorithm to determine the shortest path from node.pdf1) Use Link State algorithm to determine the shortest path from node.pdf
1) Use Link State algorithm to determine the shortest path from node.pdf
 
1) Un �rea fue destruida recientemente por un furioso incendio fores.pdf
1) Un �rea fue destruida recientemente por un furioso incendio fores.pdf1) Un �rea fue destruida recientemente por un furioso incendio fores.pdf
1) Un �rea fue destruida recientemente por un furioso incendio fores.pdf
 
1) Statements detailing a companys expectations for its employees .pdf
1) Statements detailing a companys expectations for its employees .pdf1) Statements detailing a companys expectations for its employees .pdf
1) Statements detailing a companys expectations for its employees .pdf
 
1) Select the correct order for the steps of corporate social respon.pdf
1) Select the correct order for the steps of corporate social respon.pdf1) Select the correct order for the steps of corporate social respon.pdf
1) Select the correct order for the steps of corporate social respon.pdf
 
1) Las especies con tiempos de generaci�n m�s largos deben tener .pdf
1) Las especies con tiempos de generaci�n m�s largos deben tener .pdf1) Las especies con tiempos de generaci�n m�s largos deben tener .pdf
1) Las especies con tiempos de generaci�n m�s largos deben tener .pdf
 
1) Seg�n Henri Fayol, los planes efectivos deben tener las cualidade.pdf
1) Seg�n Henri Fayol, los planes efectivos deben tener las cualidade.pdf1) Seg�n Henri Fayol, los planes efectivos deben tener las cualidade.pdf
1) Seg�n Henri Fayol, los planes efectivos deben tener las cualidade.pdf
 
1) Run the systemctl status httpd command to show that your web se.pdf
1) Run the systemctl status httpd command to show that your web se.pdf1) Run the systemctl status httpd command to show that your web se.pdf
1) Run the systemctl status httpd command to show that your web se.pdf
 
1) La siguiente oraci�n tiene errores, podr�a ser prolija, entrecort.pdf
1) La siguiente oraci�n tiene errores, podr�a ser prolija, entrecort.pdf1) La siguiente oraci�n tiene errores, podr�a ser prolija, entrecort.pdf
1) La siguiente oraci�n tiene errores, podr�a ser prolija, entrecort.pdf
 
1) In the study of an outbreak of an infectious disease, plotting an.pdf
1) In the study of an outbreak of an infectious disease, plotting an.pdf1) In the study of an outbreak of an infectious disease, plotting an.pdf
1) In the study of an outbreak of an infectious disease, plotting an.pdf
 
1) Install and run an Apache secure web server on your Linux OS. 2) .pdf
1) Install and run an Apache secure web server on your Linux OS. 2) .pdf1) Install and run an Apache secure web server on your Linux OS. 2) .pdf
1) Install and run an Apache secure web server on your Linux OS. 2) .pdf
 
1) La expresi�n g�nica diferencial ocurre en cada una de las siguien.pdf
1) La expresi�n g�nica diferencial ocurre en cada una de las siguien.pdf1) La expresi�n g�nica diferencial ocurre en cada una de las siguien.pdf
1) La expresi�n g�nica diferencial ocurre en cada una de las siguien.pdf
 
1) El objetivo del inventario de seguridad es a. reemplace las uni.pdf
1) El objetivo del inventario de seguridad es a. reemplace las uni.pdf1) El objetivo del inventario de seguridad es a. reemplace las uni.pdf
1) El objetivo del inventario de seguridad es a. reemplace las uni.pdf
 
1) Explicar qu� es la gesti�n de la capacidad y por qu� es estrat�gi.pdf
1) Explicar qu� es la gesti�n de la capacidad y por qu� es estrat�gi.pdf1) Explicar qu� es la gesti�n de la capacidad y por qu� es estrat�gi.pdf
1) Explicar qu� es la gesti�n de la capacidad y por qu� es estrat�gi.pdf
 
1) En una poblaci�n que est� en equilibrio de Hardy-Weinberg, hay do.pdf
1) En una poblaci�n que est� en equilibrio de Hardy-Weinberg, hay do.pdf1) En una poblaci�n que est� en equilibrio de Hardy-Weinberg, hay do.pdf
1) En una poblaci�n que est� en equilibrio de Hardy-Weinberg, hay do.pdf
 
1) Eres un estudiante de MPH en pr�cticas en una iglesia local. Part.pdf
1) Eres un estudiante de MPH en pr�cticas en una iglesia local. Part.pdf1) Eres un estudiante de MPH en pr�cticas en una iglesia local. Part.pdf
1) Eres un estudiante de MPH en pr�cticas en una iglesia local. Part.pdf
 

Recently uploaded

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Recently uploaded (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 

-JAVA-provide a test class that do the required -you may add met.pdf

  • 1. -JAVA- provide a test class that do the required -you may add methods you need in the SLL- //************************** SLL.java ********************************* // a generic singly linked list class public class SLL{ private class SLLNode { private T info; private SLLNode next; public SLLNode() { this(null,null); } public SLLNode(T el) { this(el,null); } public SLLNode(T el, SLLNode ptr) { info = el; next = ptr; } } protected SLLNode head, tail; public SLL() { head = tail = null; } public boolean isEmpty() { return head == null; } public void addToHead(T el) { head = new SLLNode(el,head); if (tail == null) tail = head; } public void addToTail(T el) { if (!isEmpty()) { tail.next = new SLLNode(el); tail = tail.next;
  • 2. } else head = tail = new SLLNode(el); } public T deleteFromHead() { // delete the head and return its info; if (isEmpty()) return null; T el = head.info; if (head == tail) // if only one node on the list; head = tail = null; else head = head.next; return el; } public T deleteFromTail() { // delete the tail and return its info; if (isEmpty()) return null; T el = tail.info; if (head == tail) // if only one node in the list; head = tail = null; else { // if more than one node in the list, SLLNode tmp; // find the predecessor of tail; for (tmp = head; tmp.next != tail; tmp = tmp.next); tail = tmp; // the predecessor of tail becomes tail; tail.next = null; } return el; } public void delete(T el) { // delete the node with an element el; if (!isEmpty()) if (head == tail && el.equals(head.info)) // if only one head = tail = null; // node on the list; else if (el.equals(head.info)) // if more than one node on the list; head = head.next; // and el is in the head node; else { // if more than one node in the list SLLNode pred, tmp;// and el is in a nonhead node; for (pred = head, tmp = head.next; tmp != null && !tmp.info.equals(el);
  • 3. pred = pred.next, tmp = tmp.next); if (tmp != null) { // if el was found; pred.next = tmp.next; if (tmp == tail) // if el is in the last node; tail = pred; } } } @Override public String toString() { if(head == null) return "[ ]"; String str = "[ "; SLLNode tmp = head; while(tmp != null){ str += tmp.info + " "; tmp = tmp.next; } return str+"]"; } public boolean contains(T el) { if(head == null) return false; SLLNode tmp = head; while(tmp != null){ if(tmp.info.equals(el)) return true; tmp = tmp.next; } return false; } public int size(){ if(head == null)
  • 4. return 0; int count = 0; SLLNode p = head; while(p != null) { count++; p = p.next; } return count; } // // Please write the methods of Task02 here: // public void insertBefore(int index, T newElem) throws Exception { //throws exception if the list is empty if(isEmpty()){ throw new Exception("list is empty"); } //inserts if(index < size()){ if (index == 0){ SLLNode newnode = new SLLNode<>(newElem, head); head = newnode; } else{ SLLNode temp = head; SLLNode newnode = new SLLNode<>(newElem, null); for (int i = 0; i < index - 1; i++) { temp = temp.next; } newnode.next = temp.next; temp.next = newnode; }
  • 5. } //throws exception for invalid index else { throw new Exception("index is not valid"); } } public T delete(int index) throws Exception{ //throws exception if the list is empty if (isEmpty()) { throw new Exception("list is empty"); } //removes if (index < size()) { if (index == 0) { return deleteFromHead(); } else if (index == size() - 1) { return deleteFromTail(); } SLLNode temp = head; for (int i = 0; i < index - 1; i++) { temp = temp.next; } T elm = temp.next.info; temp.next = temp.next.next; return elm; } //invalid index throw new Exception("index is not valid"); } public void insertAfterSecondOccurrence(T e1, T e2) throws Exception {
  • 6. //throws exception if the list is empty if (isEmpty()) { throw new Exception("list is empty"); } //inserts int pos = -1; int counter = 0; SLLNode temp = head; for (int i = 0; i < size(); i++) { if (temp.info == e2) { counter++; } if (counter == 2) { pos = i; break; } temp = temp.next; } if (pos != -1) { if (pos + 1 == size()) { addToTail(e1); } else { insertBefore(pos + 1, e1); } } //the list has no second occurrence of e2 if (pos == -1){ throw new Exception("list has no second occurrence of " + e2); } } } Part I: Programming (50 points) Use the singly linked list class introduced in the lab to implement integers of unlimited size. Each node of the list should store one digit of the integer. You are to implement the addition, subtraction and multiplication operations. Please note that any additional data structure to be used in solving this problem has to be taken from the ones introduced in the ICS 202 lab. In addition, provide a test class that will do the following: It will
  • 7. keep asking the user to enter two integers, choose one of the operations (addition, subtraction, multiplication) and then display the result. The program will stop upon entering the "#" character (without the double quotes).