SlideShare a Scribd company logo
import java.util.Iterator;
import java.util.NoSuchElementException;
import lab4.util.List;
public class SinglyLinkedList<E> implements List<E> {
@SuppressWarnings("hiding")
private class SinglyLinkedListIterator<E> implements Iterator<E>{
private Node<E> nextNode;
@SuppressWarnings("unchecked")
public SinglyLinkedListIterator() {
this.nextNode = (Node<E>) header.getNext();
}
@Override
public boolean hasNext() {
return nextNode != null;
}
@Override
public E next() {
if (this.hasNext()) {
E result = this.nextNode.getElement();
this.nextNode = this.nextNode.getNext();
return result;
}
else {
throw new NoSuchElementException();
}
}
}
private static class Node<E> {
private E element;
private Node<E> next;
public Node(E element, Node<E> next) {
super();
this.element = element;
this.next = next;
}
public Node() {
super();
}
public E getElement() {
return element;
}
public void setElement(E element) {
this.element = element;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
private Node<E> header;
private int currentSize;
public SinglyLinkedList() {
this.header = new Node<>();
this.currentSize = 0;
}
@Override
public int size() {
return this.currentSize;
}
@Override
public boolean isEmpty() {
return this.size() == 0;
}
@Override
public boolean contains(E e) {
return this.firstIndexOf(e) >= 0;
}
@Override
public int firstIndexOf(E e) {
int i = 0;
for (Node<E> temp = this.header.getNext(); temp != null;
temp = temp.getNext(), ++i) {
if (temp.getElement().equals(e)) {
return i;
}
}
// not found
return -1;
}
@Override
public void add(E e) {
if (this.isEmpty()) {
this.header.setNext(new Node<E>(e, null));
this.currentSize++;
}
else {
Node<E>temp= this.header.getNext();
while (temp.getNext() != null) {
temp = temp.getNext();
}
Node<E> newNode = new Node<>(e, null);
temp.setNext(newNode);
this.currentSize++;
}
}
@Override
public void add(E e, int index) {
if ((index < 0) || (index > this.currentSize)) {
throw new IndexOutOfBoundsException();
}
if (index == this.currentSize) {
this.add(e);
}
else {
Node<E> temp = null;
if (index == 0) {
temp = this.header;
}
else {
temp = this.getPosition(index -1);
}
Node<E> newNode = new Node<>();
newNode.setElement(e);
newNode.setNext(temp.getNext());
temp.setNext(newNode);
this.currentSize++;
}
}
@Override
public E get(int position) {
if ((position < 0) || position >= this.currentSize) {
throw new IndexOutOfBoundsException();
}
Node<E> temp = this.getPosition(position);
return temp.getElement();
}
private Node<E> getPosition(int index){
int currentPosition=0;
Node<E> temp = this.header.getNext();
while(currentPosition != index) {
temp = temp.getNext();
currentPosition++;
}
return temp;
}
@Override
public boolean remove(int index) {
if ((index < 0) || (index >= this.currentSize)){
throw new IndexOutOfBoundsException();
}
else {
Node<E> temp = this.header;
int currentPosition =0;
Node<E> target = null;
while (currentPosition != index) {
temp = temp.getNext();
currentPosition++;
}
target = temp.getNext();
temp.setNext(target.getNext());
target.setElement(null);
target.setNext(null);
this.currentSize--;
return true;
}
}
@Override
public E set(int position, E newElement) {
if ((position < 0) || position >= this.currentSize) {
throw new IndexOutOfBoundsException();
}
Node<E> temp = this.getPosition(position);
E result = temp.getElement();
temp.setElement(newElement);
return result;
}
@Override
public void clear() {
while(!this.isEmpty()) {
this.remove(0);
}
}
@Override
public Iterator<E> iterator() {
return new SinglyLinkedListIterator<E>();
}
@Override
public int lastIndexOf(E e) {
int i = 0, result = -1;
for (Node<E> temp = this.header.getNext(); temp != null;
temp = temp.getNext(), ++i) {
if (temp.getElement().equals(e)) {
result = i;
}
}
// not found
return result;
}
@Override
public E first() {
return get(0);
}
@Override
public E last() {
return get(size() - 1);
}
@Override
public boolean remove(E e) {
int i = this.firstIndexOf(e);
if (i < 0) {
return false;
}else {
this.remove(i);
return true;
}
}
@Override
public int removeAll(E e) {
int count = 0;
while (this.remove(e)) {
count++;
}
return count;
}
/**
* TODO EXERCISE 1:
* Implement an O(n) member method called reverse()
* which reverses the elements in a list with n elements.
*
* For example, if L = {Ken, Al, Bob, Mel} then a call to L.reverse() turns L into
* L = {Mel, Bob, Al, Ken}.
*
* Note: A call to reverse() modifies the contents of the list L, it does not
* create a copy of L.
*/
public void reverse() {
/*TODO ADD YOUR CODE HERE*/
}
}
5. (20 pts) Head over to Hasprefixsumproblem. java after finishing exercise 4. The instructions
for this exercise are as follows: - Implement a method that determines if a LinkedList has an
initial sequence of nodes whose values sum to n. If so, it returns an integer corresponding to how
many elements at the beginning of the list add up to n . - The method receives as parameter a
Node that represents the head node of a singlyLinkedList, as well as an integer n denoting a
target sum to search for. - It is assumed that the List always has at least one node. - All the
elements in the List are assumed to be non-negative integers. - If no sequence of initial elements
adds up to n , the method will return a negative value, which is specified as follows: 1. The
negative of the size of the List if the sum of all elements in the List is less than n . 2. The
negative of the minimum number of elements at the beginning of the List whose sum exceeds n .
Examples (these show the lists as arrays, but you will only be given the head node of each singly
linked list) 1. A call to hasprefixsum ({ 1 , 2 , 3 , 4 , 5 } , 10 ) returns 4 since 1 + 2 + 3 + 4 = 10 ,
which is an exact sum of 10 with the first 4 elements of the list. 2. A call to hasprefixsum ({ 2 , 4
, 6 , 8 , 10 } , 10 ) returns 3 since 2 + 4 + 6 = 12 , which is larger than 10. 3. A call to
hasprefixsum ({ 1 , 2 , 3 , 4 } , 15 ) returns 4 since 1 + 2 + 3 + 4 = 10 , which is smaller than 15
and the list does not have enough elements to sum up to 15

More Related Content

PDF
public class MyLinkedListltE extends ComparableltEgtg.pdf
PDF
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
PDF
STAGE 2 The Methods 65 points Implement all the methods t.pdf
PDF
Given below is the completed implementation of MyLinkedList class. O.pdf
DOCX
Note- Can someone help me with the private E get(int index- int curren (1).docx
PDF
Note- Can someone help me with the Public boolean add(E value) method.pdf
PDF
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
PDF
Hi,I have added the methods and main class as per your requirement.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdf
Given below is the completed implementation of MyLinkedList class. O.pdf
Note- Can someone help me with the private E get(int index- int curren (1).docx
Note- Can someone help me with the Public boolean add(E value) method.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
Hi,I have added the methods and main class as per your requirement.pdf

Similar to import java-util-Iterator- import java-util-NoSuchElementException- im.pdf (20)

PDF
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
PDF
Fix my codeCode.pdf
PDF
Describe an algorithm for concatenating two singly linked lists L and.pdf
PDF
You can list anything, it doesnt matter. I just want to see code f.pdf
PDF
import java-util--- public class MyLinkedList{ public static void.pdf
PDF
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
PDF
hi i have to write a java program involving link lists. i have a pro.pdf
PDF
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
PDF
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
DOCX
Please complete all the code as per instructions in Java programming.docx
PDF
please read below it will tell you what we are using L.pdf
DOCX
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
PDF
There are a couple of new methods that you will be writing for this pr.pdf
PDF
Please help me to make a programming project I have to sue them today- (1).pdf
PDF
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
PDF
package linkedLists- import java-util-Iterator- --- A class representi.pdf
PDF
The LinkedList1 class implements a Linked list. class.pdf
PDF
File LinkedList.java Defines a doubly-l.pdf
PDF
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
PDF
Linked List Leetcode - Easy Collections - Interview Questions Java
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
Fix my codeCode.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdf
You can list anything, it doesnt matter. I just want to see code f.pdf
import java-util--- public class MyLinkedList{ public static void.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
Please complete all the code as per instructions in Java programming.docx
please read below it will tell you what we are using L.pdf
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
There are a couple of new methods that you will be writing for this pr.pdf
Please help me to make a programming project I have to sue them today- (1).pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
package linkedLists- import java-util-Iterator- --- A class representi.pdf
The LinkedList1 class implements a Linked list. class.pdf
File LinkedList.java Defines a doubly-l.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Linked List Leetcode - Easy Collections - Interview Questions Java
Ad

More from Stewart29UReesa (20)

PDF
Note- E0- Equilibrium demand and supply for labour - DL- Demand for la.pdf
PDF
need in c language Write a function called isIsoceles that accepts thr.pdf
PDF
need in c language Write the body of a function called sumRange that a.pdf
PDF
Need help with this ASAP- This is Database systems- Please draw out th.pdf
PDF
Nheser- Thmus dependest artigert- Thetrus insepensient andigeta- both.pdf
PDF
Nikke has just received an amended assessment from the Australian Taxa.pdf
PDF
Orange- Below is a sequence alignment with fixed differences for speci.pdf
PDF
Nordic Multinationals Nordic countries have small populations ( 6 mill.pdf
PDF
Nordic countries have small populations (6 million in Denmark- 9 milli.pdf
PDF
Ontinostatic typotension Vazodepressor Syncope Shuazanat SyncopeMoveme.pdf
PDF
One of the concerns in severe ankle sprain is that the patient has sus.pdf
PDF
no more info Given the system represented by the equations- x1-x22x13.pdf
PDF
On June 13- the board of directors of Siewert Incorporated declared a.pdf
PDF
On May 1- 2023- Romy and Vic formed a partnership contributing assets.pdf
PDF
On January 1- 2020- Fisher Corporation purchased 40 percent (90-000 sh.pdf
PDF
need asap- thank you Symbols for Relational Aleebra Expressions and Ot.pdf
PDF
On December 30- 2020- Inge Co-'s Board of Directors declared a 10- sto.pdf
PDF
On December 10- YR08 the board of directors of Apple Inc- declared a c.pdf
PDF
Objective- Write syntactically correct while-for loops Given a list of.pdf
PDF
Observe the Psilotum photos above- and the fern photos below- On what.pdf
Note- E0- Equilibrium demand and supply for labour - DL- Demand for la.pdf
need in c language Write a function called isIsoceles that accepts thr.pdf
need in c language Write the body of a function called sumRange that a.pdf
Need help with this ASAP- This is Database systems- Please draw out th.pdf
Nheser- Thmus dependest artigert- Thetrus insepensient andigeta- both.pdf
Nikke has just received an amended assessment from the Australian Taxa.pdf
Orange- Below is a sequence alignment with fixed differences for speci.pdf
Nordic Multinationals Nordic countries have small populations ( 6 mill.pdf
Nordic countries have small populations (6 million in Denmark- 9 milli.pdf
Ontinostatic typotension Vazodepressor Syncope Shuazanat SyncopeMoveme.pdf
One of the concerns in severe ankle sprain is that the patient has sus.pdf
no more info Given the system represented by the equations- x1-x22x13.pdf
On June 13- the board of directors of Siewert Incorporated declared a.pdf
On May 1- 2023- Romy and Vic formed a partnership contributing assets.pdf
On January 1- 2020- Fisher Corporation purchased 40 percent (90-000 sh.pdf
need asap- thank you Symbols for Relational Aleebra Expressions and Ot.pdf
On December 30- 2020- Inge Co-'s Board of Directors declared a 10- sto.pdf
On December 10- YR08 the board of directors of Apple Inc- declared a c.pdf
Objective- Write syntactically correct while-for loops Given a list of.pdf
Observe the Psilotum photos above- and the fern photos below- On what.pdf
Ad

Recently uploaded (20)

PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Complications of Minimal Access Surgery at WLH
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Pharma ospi slides which help in ospi learning
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Weekly quiz Compilation Jan -July 25.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Orientation - ARALprogram of Deped to the Parents.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Final Presentation General Medicine 03-08-2024.pptx
Complications of Minimal Access Surgery at WLH
O7-L3 Supply Chain Operations - ICLT Program
Microbial disease of the cardiovascular and lymphatic systems
Pharma ospi slides which help in ospi learning
Chinmaya Tiranga quiz Grand Finale.pdf
Cell Types and Its function , kingdom of life
Abdominal Access Techniques with Prof. Dr. R K Mishra
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Weekly quiz Compilation Jan -July 25.pdf
Cell Structure & Organelles in detailed.
Pharmacology of Heart Failure /Pharmacotherapy of CHF

import java-util-Iterator- import java-util-NoSuchElementException- im.pdf

  • 1. import java.util.Iterator; import java.util.NoSuchElementException; import lab4.util.List; public class SinglyLinkedList<E> implements List<E> { @SuppressWarnings("hiding") private class SinglyLinkedListIterator<E> implements Iterator<E>{ private Node<E> nextNode; @SuppressWarnings("unchecked") public SinglyLinkedListIterator() { this.nextNode = (Node<E>) header.getNext(); } @Override public boolean hasNext() { return nextNode != null; } @Override public E next() { if (this.hasNext()) { E result = this.nextNode.getElement(); this.nextNode = this.nextNode.getNext(); return result; } else { throw new NoSuchElementException(); } } } private static class Node<E> { private E element; private Node<E> next; public Node(E element, Node<E> next) { super(); this.element = element; this.next = next; } public Node() {
  • 2. super(); } public E getElement() { return element; } public void setElement(E element) { this.element = element; } public Node<E> getNext() { return next; } public void setNext(Node<E> next) { this.next = next; } } private Node<E> header; private int currentSize; public SinglyLinkedList() { this.header = new Node<>(); this.currentSize = 0; } @Override public int size() { return this.currentSize; } @Override public boolean isEmpty() { return this.size() == 0; } @Override public boolean contains(E e) { return this.firstIndexOf(e) >= 0; } @Override public int firstIndexOf(E e) { int i = 0;
  • 3. for (Node<E> temp = this.header.getNext(); temp != null; temp = temp.getNext(), ++i) { if (temp.getElement().equals(e)) { return i; } } // not found return -1; } @Override public void add(E e) { if (this.isEmpty()) { this.header.setNext(new Node<E>(e, null)); this.currentSize++; } else { Node<E>temp= this.header.getNext(); while (temp.getNext() != null) { temp = temp.getNext(); } Node<E> newNode = new Node<>(e, null); temp.setNext(newNode); this.currentSize++; } } @Override public void add(E e, int index) { if ((index < 0) || (index > this.currentSize)) { throw new IndexOutOfBoundsException(); } if (index == this.currentSize) { this.add(e); } else { Node<E> temp = null; if (index == 0) { temp = this.header; } else { temp = this.getPosition(index -1); } Node<E> newNode = new Node<>(); newNode.setElement(e);
  • 4. newNode.setNext(temp.getNext()); temp.setNext(newNode); this.currentSize++; } } @Override public E get(int position) { if ((position < 0) || position >= this.currentSize) { throw new IndexOutOfBoundsException(); } Node<E> temp = this.getPosition(position); return temp.getElement(); } private Node<E> getPosition(int index){ int currentPosition=0; Node<E> temp = this.header.getNext(); while(currentPosition != index) { temp = temp.getNext(); currentPosition++; } return temp; } @Override public boolean remove(int index) { if ((index < 0) || (index >= this.currentSize)){ throw new IndexOutOfBoundsException(); } else { Node<E> temp = this.header; int currentPosition =0; Node<E> target = null; while (currentPosition != index) { temp = temp.getNext(); currentPosition++; } target = temp.getNext(); temp.setNext(target.getNext()); target.setElement(null);
  • 5. target.setNext(null); this.currentSize--; return true; } } @Override public E set(int position, E newElement) { if ((position < 0) || position >= this.currentSize) { throw new IndexOutOfBoundsException(); } Node<E> temp = this.getPosition(position); E result = temp.getElement(); temp.setElement(newElement); return result; } @Override public void clear() { while(!this.isEmpty()) { this.remove(0); } } @Override public Iterator<E> iterator() { return new SinglyLinkedListIterator<E>(); } @Override public int lastIndexOf(E e) { int i = 0, result = -1; for (Node<E> temp = this.header.getNext(); temp != null; temp = temp.getNext(), ++i) { if (temp.getElement().equals(e)) { result = i; } } // not found return result; }
  • 6. @Override public E first() { return get(0); } @Override public E last() { return get(size() - 1); } @Override public boolean remove(E e) { int i = this.firstIndexOf(e); if (i < 0) { return false; }else { this.remove(i); return true; } } @Override public int removeAll(E e) { int count = 0; while (this.remove(e)) { count++; } return count; } /** * TODO EXERCISE 1: * Implement an O(n) member method called reverse() * which reverses the elements in a list with n elements. * * For example, if L = {Ken, Al, Bob, Mel} then a call to L.reverse() turns L into * L = {Mel, Bob, Al, Ken}. * * Note: A call to reverse() modifies the contents of the list L, it does not * create a copy of L. */
  • 7. public void reverse() { /*TODO ADD YOUR CODE HERE*/ } } 5. (20 pts) Head over to Hasprefixsumproblem. java after finishing exercise 4. The instructions for this exercise are as follows: - Implement a method that determines if a LinkedList has an initial sequence of nodes whose values sum to n. If so, it returns an integer corresponding to how many elements at the beginning of the list add up to n . - The method receives as parameter a Node that represents the head node of a singlyLinkedList, as well as an integer n denoting a target sum to search for. - It is assumed that the List always has at least one node. - All the elements in the List are assumed to be non-negative integers. - If no sequence of initial elements adds up to n , the method will return a negative value, which is specified as follows: 1. The negative of the size of the List if the sum of all elements in the List is less than n . 2. The negative of the minimum number of elements at the beginning of the List whose sum exceeds n . Examples (these show the lists as arrays, but you will only be given the head node of each singly linked list) 1. A call to hasprefixsum ({ 1 , 2 , 3 , 4 , 5 } , 10 ) returns 4 since 1 + 2 + 3 + 4 = 10 , which is an exact sum of 10 with the first 4 elements of the list. 2. A call to hasprefixsum ({ 2 , 4 , 6 , 8 , 10 } , 10 ) returns 3 since 2 + 4 + 6 = 12 , which is larger than 10. 3. A call to hasprefixsum ({ 1 , 2 , 3 , 4 } , 15 ) returns 4 since 1 + 2 + 3 + 4 = 10 , which is smaller than 15 and the list does not have enough elements to sum up to 15