Creating Minimum number and Addition Function of LinkedList - java

I'm having a problem with trying the logic and trying to write a min and additionMerge function and their recursive versions of the function that takes at least one list as an argument (the first node of the list). This will be a private helper function that is called by a wrapper function that is a member function of the LinkedList class.
public class LinkedList {
private static class ListNode {
public int firstItem;
public ListNode restOfList;
}
private ListNode first;
/**
* Create an empty list.
*/
public LinkedList() {
first = null;
}
public LinkedList(int n) {
first = countDown(n);
}
public LinkedList(String s) {
String[] temp = s.split(",");
for (int i = temp.length-1; i >= 0; i--) {
first = insertAtFront(first, Integer.parseInt(temp[i]));
}
}
public int length() {
return length(first);
}
private static int length(ListNode list) {
if (list == null) {
return 0;
}
int temp = length(list.restOfList);
return temp + 1;
}
public boolean contains(int value) {
return contains(first, value);
}
private static boolean contains(ListNode list, int value) {
if (list == null) {
return false;
}
if (list.firstItem == value) {
return true;
}
return contains(list.restOfList, value);
}
public int sum() {
return sum(first);
}
private static int sum(ListNode list) {
if (list == null) {
return 0;
}
return sum(list.restOfList) + list.firstItem;
}
public int count(int target) {
return count(first, target);
}
private static int count(ListNode list, int target) {
if (list == null) {
return 0;
}
int temp = count(list.restOfList, target);
if (list.firstItem == target) {
temp++;
}
return temp;
}
public void replace(int oldValue, int newValue) {
replace(first, oldValue, newValue);
}
private static void replace(ListNode list, int oldValue, int newValue) {
if (list == null) {
return;
}
replace(list.restOfList, oldValue, newValue);
if (list.firstItem == oldValue) {
list.firstItem = newValue;
}
}
public void insertAtFront(int n) {
first = insertAtFront(first, n);
}
private static ListNode insertAtFront(ListNode list, int n) {
ListNode answer = new ListNode();
answer.firstItem = n;
answer.restOfList = list;
return answer;
}
private static ListNode countDown(int n) {
if (n == 1) {
ListNode answer = new ListNode();
answer.firstItem = 1;
answer.restOfList = null;
return answer;
}
ListNode temp = countDown(n - 1);
ListNode answer = insertAtFront(temp, n);
return answer;
}
public void insertAtBack(int item) {
first = insertAtBack(first, item);
}
private static ListNode insertAtBack(ListNode list, int item) {
if (list == null) {
ListNode answer = new ListNode();
answer.firstItem = item;
answer.restOfList = null;
return answer;
}
//List answer = new ListNode();
//answer.firstItem = list.firstItem;
ListNode temp = insertAtBack(list.restOfList, item);
//answer.restOfList = temp;
list.restOfList = temp;
return list;
}
public void concatenate(LinkedList otherList) {
this.first = concatenate(this.first, otherList.first);
}
private static ListNode concatenate(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
ListNode temp = concatenate(list1.restOfList, list2);
list1.restOfList = temp;
return list1;
}
public void filter(int item) {
first = filter(first, item);
}
#Override
public String toString() {
if (first == null) {
return "";
}
StringBuilder sb = new StringBuilder(256);
sb.append(first.firstItem);
for (ListNode current = first.restOfList;
current != null;
current = current.restOfList) {
sb.append(',');
sb.append(current.firstItem);
}
return sb.toString();
}
private static ListNode filter(ListNode list, int item) {
if (list == null) {
return null;
}
ListNode temp = filter(list.restOfList, item);
if (list.firstItem == item) {
return temp;
}
list.restOfList = temp;
return list;
}
public int min() throws RuntimeException {
if (first == null)
throw new RuntimeException("List is Empty");
else
return min();
}
// * A private recursive helper function that returns the minimum item in a
* list whose first node is the argument list.
private static int min(ListNode list) throws RuntimeException {
if (list == null) {
return 0;
}
}
public void additionMerge(LinkedList l2) {
}
* Every node in the list that begins with node
* node1 is increased by the ammount of the corresponding
* node in the list that begins with node node2.
* If one list is longer than the other, the missing nodes
* in the shorter list are assumed to be 0.
private static ListNode additionMerge(ListNode node1, ListNode node2) {
if (list == null) {
return null;
}
}
}

If this is not homework, then my advice is:
Don't write your own LinkedList class. Use the existing out, and add the extra functionality either as a helper class or by extending the existing class.
If you do decide to implement your own linked list class, then you should beware of using recursion. Recursion gives a neat soltion, but there is a major drawback with recursion in Java. The JVM does not do tail call optimization, so a recusive algorithm that recurses deeply (e.g. recursively traversing a long list) is liable to cause a StackOverflowError.

Related

How to extend child classes with a parent interface class

interface Iterator {
boolean hasnext();
int next();
}
class practice5 {
public static void main(String a[]) {
Stack s = new Stack();
Queue q = new Queue();
Linkedlist l = new Linkedlist();
s.push(100);
s.push(200);
q.Enque(300);
q.Enque(400);
l.add(500);
l.add(600);
Iterator itr;
itr = s;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = q;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = l;
while (itr.hasnext()) {
System.out.println(itr.next());
}
}
}
class Stack extends Iterator {
private int stack[];
private int top;
public Stack() {
stack = new int[10];
top = -1;
}
public void push(int val) {
top++;
stack[top] = val;
}
public boolean hasnext() {
if (top >= 0) {
return false;
} else {
return true;
}
}
public int next() {
return (stack[top--]);
}
}
class Queue extends Iterator {
private int queue[];
private int front, rear;
public Queue() {
queue = new int[10];
front = 0;
rear = 0;
}
public void Enque(int val) {
queue[rear] = val;
rear++;
}
public boolean hasnext() {
if (front < rear) {
return false;
} else {
return true;
}
}
public int next() {
return (queue[front++]);
}
}
class Linkedlist extends Iterator {
private int data;
private Linkedlist nw, next, prev, first, guest;
public Linkedlist() {
nw = next = prev = first = null;
}
public void add(int val) {
nw = new Linkedlist();
nw.data = val;
if (first == null) {
prev = first = nw;
} else {
prev.next = nw;
prev = nw;
}
}
public boolean hasnext() {
if (guest != 0) {
return true;
} else {
return false;
}
}
public int next() {
int curval;
curval = first.data;
first = first.next;
return (curval);
}
}
I'm expecting that I get an output for the above code.
I need to know if I'm extending the Stack, Queue and LinkedList classes wrongly with the interface class. Whenever I'm pass the iterator class object the instance of my child class objects, I am getting an error.
Also, in the LinkedList section when I call guest != 0, I'm getting an error Bad Operand. How can I check and print whether my guest is equal to zero or not?

how to do Junit for shallow/deep copy of LinkedList

hello there i did the deep copy and the shallow copy is suggested by the user AndyMan and now i did the JUnit and im having a slight problem making those tests:
1.deep copy method
public ListNode<E> deep_clone() {
first = deep_clone(first);
ListNode<E> copy = new ListNode<>(first);
return copy;
}
private static Node deep_clone(Node head) {
if (head == null) {
return null;
}
Node temp = new Node(head.getData());
temp.setNext(deep_clone(head.getNext()));
return temp;
}
Edit
many thanks for AndyMan for suggesting this shallow copy method:
private static Node shallow_clone(Node head) {
if (head == null)
return null;
Node temp = new Node(head.getData());
temp.setNext(head.getNext()); // Just copy the reference
return temp;
}
but one question though how to Junit both the deep and shallow copy methods?
i did the following and i got a failed Junit test:
#Test
public void test_shallow_clone(){
ListNode<Integer> list =new ListNode<>();
for (int i = 0; i < 10; i++)
list.insert(i);
ListNode<Integer>cloned =list.shallow_clone();
//assertSame(cloned,list); //failed i dont know why
//assertEquals(cloned, list);//Even though its shallow copy i get that they are not equal!
assertSame(list.getFirst(), cloned.getFirst());
assertTrue(cloned.equals(list));
}
and the test for the deep copy:
#Test
public void test_depp_clone(){
ListNode<Integer> list =new ListNode<>();
for (int i = 0; i < 10; i++)
list.insert(i);
ListNode<Integer>cloned =list.depp_clone();
assertSame(cloned.getFirst(),list.getFirst());//check for same val..
//assertEquals(cloned, list);//this make the test fail..
assertFalse(cloned.equals(list));//okay the are not equal lists this means its deep copy...no implemented equal method :)
}
class ListNode
public class ListNode<E> implements Iterable<E>{
private Node<E> first;
//private Node<E> last;
public ListNode() {
first = null;
//last = null;
}
public ListNode(Node head) {
this.first = head;
//this.last = this.first;
}
public ListNode(E data) {
Node head = new Node(data);
this.first = head;
//this.last = this.first;
}
#Override
public Iterator<E> iterator() {
return new LL_Iterator<>(first);
}
private static class Node<E> {
private E data;
private Node next;
public Node() {
this.data = null;
this.next = null;
}
public Node(E data) {
this.data = data;
next = null;
}
public Node(E data, Node next) {
this.data = data;
this.next = null;
}
public E getData() {
return data;
}
public void setData(E val) {
this.data = val;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
#Override
public String toString() {
return "Node{" + "data=" + data + ", next=" + next + '}';
}
}
private static class LL_Iterator<E> implements Iterator<E> {
private Node<E> curr;//we have to specify the E here because if we dont we have to cast the curr.getData()
public LL_Iterator(Node head) {
curr = head;
}
#Override
public boolean hasNext() {
return curr != null;
}
#Override
public E next() {
if (hasNext()) {
E data = curr.getData();
curr = curr.getNext();
return data;
}
return null;
}
}
public E getFirst(){
if(first==null)
return null;
return first.getData();
}
public boolean addFirst (E data) {
if(data==null)
return false;
Node t= new Node (data);
t.setNext(first);
first=t;
return true;
}
public E getLast() {
if (first==null)
return null;
return getLast(first).getData();
}
private static<E> Node<E> getLast(Node<E> head) {
if (head == null) {
return null;
}
Node temp = head;
if (temp.getNext() != null) {
temp = getLast(temp.getNext());
}
return temp;
}
//insertion....Wie setLast
public boolean insert(E data) {
if(data==null)
return false;
first = insert(first, data);
//last = getLast();
return true;
}
private static <E> Node insert(Node head, E data) {
if (head == null) {
return new Node(data);
} else {
head.setNext(insert(head.getNext(), data));
}
return head;
}
public void printList(){
LL_Iterator it= new LL_Iterator(first);
printUsingIterator(it,it.next());
}
private static<E> void printUsingIterator (LL_Iterator it, E data){
//VERDAMMT MAL RHEINFOLGE DER ANWEISUNGEN MACHT UNTERSCHIED
System.out.print(data+"->");
if (!it.hasNext()) {
System.out.print(it.next()+"\n");//THIS WILL PRINT NULL!!!
return;
}
printUsingIterator(it,it.next());
}
public int size() {
return size(first);
}
private static int size(Node head) {
if (head == null) {
return 0;
} else {
return 1 + size(head.getNext());
}
}
public boolean contains(E data) {
return contains(first, data);
}
public static <E> boolean contains(Node head, E data) {
if (head == null || data == null) {
return false;
}
if (head.getData().equals(data)) {
return true;
}
return contains(head.getNext(), data);
}
public int countIf(E t) {
return countIf(first, t);
}
private static <E> int countIf(Node head, E t) {
if (head == null ||t ==null) {
return 0;
}
if (head.getData().equals(t)) {
return 1 + countIf(head.getNext(), t);
}
return countIf(head.getNext(), t);
}
//TODO: WHY IM GETTING HERE AN OVERRIDE REQUEST FROM THE COMPILER??
//answer because im overriding the damn clone() of the list class which is shallow clone
public ListNode<E> depp_clone() {
first = depp_clone(first);
ListNode<E> copy = new ListNode<>(first);
return copy;
}
private static Node depp_clone(Node head) {
if (head == null) {
return null;
}
Node temp = new Node(head.getData());
temp.setNext(depp_clone(head.getNext()));
return temp;
}
public ListNode shallow_clone (){
ListNode<E> cloned=new ListNode<>(shallow_clone(first));
return cloned;
}
private static Node shallow_clone(Node head) {
if (head == null)
return null;
Node temp = new Node(head.getData());
temp.setNext(head.getNext()); // Just copy the reference
return temp;
}
Say head points to node0 which points to node1:
head = node0 => node1
In a deep copy, create two new nodes 7 and 8:
deepCopy = node7 => node6
In a shallow copy, create one new node 7 and copy reference to original node:
shallowCopy = node7 => node1
private static Node shallow_clone(Node head) {
if (head == null) {
return null;
}
Node temp = new Node(head.getData());
temp.setNext(head.getNext()); // Just copy the reference
return temp;
}
If the original node1 is changed, it will affect both the original and the shallow copy. it will not affect the deep copy.
Now for the terminology. What has been described is how to deep copy or shallow copy a node. It does not really make sense to shallow copy a linked list, because you are really just shallow coping a single node. Of course you can deep copy the list.
If it were an array, rather than a linked list, then you could shallow or deep copy.
To test these, override equals() and hashCode(). I would consider two lists equal if they have the same values. For two nodes to be equal, they should have the same value, and the rest of the list should be equal. If you don't override equals(), the implementation in Object is used. Object uses a bitwise comparison requiring the same references. You may want to look this up.
Also when overriding equals(), hashCode() needs to be overriden too. This is not directly related to the question, so you may want to look it after.
ListNode equals() and hashCode():
#Override
public boolean equals(Object otherObject) {
// Objects are equal if they have the same value, and next has the same value
if (otherObject instanceof ListNode) {
ListNode other = (ListNode)otherObject;
return first.equals(other.first);
}
else {
return false;
}
}
#Override
public int hashCode() {
return first.hashCode();
}
Node equals() and hashCode():
#Override
public boolean equals(Object otherObject) {
// Objects are equal if they have the same value, && next has the same value
if (otherObject instanceof Node) {
Node other = (Node)otherObject;
return data.equals(other.data) && ((next == null && ((Node) otherObject).getNext() == null) || next.equals(((Node) otherObject).next));
}
else {
return false;
}
}
#Override
public int hashCode() {
return data.hashCode();
}

Java linked list how to make a private method to handle searching

I trying and need help on how to create a private method to search a singly linked list.
My private search method is all the way at the bottom, how can I create a private method so i can then use it in an add/delete method?
I have been trying to do this for hours and I can't seem to get it right, i want to make a private search method to avoid loops later on in my other methods such as find add delete
public class LinkedBag<T> {
private Node first;
private int n;
public LinkedBag() {
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void add(T item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
public int search(T item) {
if(item == null) {
throw new IllegalArgumentException("Cannot search null");
}
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
private class Node {
private T item;
private Node next;
}
public static void main(String[] args) {
LinkedBag<Integer> intBag = new LinkedBag<>();
intBag.add(1);
intBag.add(2);
intBag.add(3);
System.out.println(intBag.search(1) == 0);
System.out.println(intBag.search(2) == 1);
System.out.println(intBag.search(3) == 2);
System.out.println(intBag.search(4) == -1);
}
}
You can create a search method in a single linked list which returns the position of the item or e.g. -1 in case the item was not found.
This search method will need to loop from the first node through its tailing nodes sequentially, extracts the item associated to each node and uses the equals method to try to find a match with the search item.
Here is a possible implementation in Java:
public int search(T item) {
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
Below is a full example of how you can do it in a simple linked list with minimal generics support. Included is also a main method with a minimal unit test to prove the concept:
public class LinkedBag<T> {
private Node first;
private int n;
public LinkedBag() {
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void add(T item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
public int search(T item) {
if(item == null) {
throw new IllegalArgumentException("Cannot search null");
}
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
private class Node {
private T item;
private Node next;
}
public static void main(String[] args) {
LinkedBag<Integer> intBag = new LinkedBag<>();
intBag.add(1);
intBag.add(2);
intBag.add(3);
System.out.println(intBag.search(1) == 0);
System.out.println(intBag.search(2) == 1);
System.out.println(intBag.search(3) == 2);
System.out.println(intBag.search(4) == -1);
}
}

Joining two self-written doubly-LinkedLists in Java constructor

I would like to create a third list by connecting 2 others. I tried to do it, but as I expected my idea was wrong and everything doesn't work fine. Below you can see List file and test program. The other (empty) constructors of List are meant to connect 2 lists by adding elements of one List before specific index of the second list, and adding elements of one List before specific element of the second one using equals() method. It will be also hard for me for sure, but I ask only for simply connecting elements to obtain something like that:
(L11, L12, L13)+(L21, L22, L23) = L11,L12,L13,L21,L22,L23
public class Lista implements List {
private Element head = new Element(null); //wartownik
private int size;
public Lista(){
clear();
}
public Lista(Lista lista1, Lista lista2) {
head.previous = lista2.head.previous;
head.next = lista1.head.next;
}
public Lista(Lista lista1, Lista lista2, int index) {
}
public Lista(Lista lista1, Lista2. Object value) {
}
public void clear(){
head.setPrevious(head);
head.setNext(head);
size=0;
}
public void insert(int index, Object value) throws IndexOutOfBoundsException {
if (index<0 || index>size) throw new IndexOutOfBoundsException();
Element element = new Element(value);
element.wstawPrzed(getElement(index));
++size;
}
public Element getElement(int index) {
Element szukany = head.getNext();
for (int i=index; i>0; --i)
szukany = szukany.getNext();
return szukany;
}
public Object get(int index) throws IndexOutOfBoundsException{
if(index<0 || index>size) throw new IndexOutOfBoundsException();
Element particular = head.getNext();
for(int i=0; i <= index; i++)
particular = particular.getNext();
return particular.getValue();
}
public boolean delete(Object o){
if(head.getNext() == null) return false;
if(head.getNext().getValue().equals(o)){
head.setNext(head.getNext().getNext());
size--;
return true;
}
Element delete = head.getNext();
while(delete != null && delete.getNext() != null){
if(delete.getNext().getValue().equals(o)){
delete.setNext(delete.getNext().getNext());
size--;
return true;
}
delete = delete.getNext();
}
return false;
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public void infoOStanie() {
if (isEmpty()) {
System.out.println("Lista pusta.");
}
else
{
System.out.println("Lista zawiera " + size() + " elementow.");
}
}
public IteratorListowy iterator() {
return new IteratorListowy();
}
public void wyswietlListe() {
System.out.println();
IteratorListowy iterator = iterator();
for (iterator.first(); !iterator.isDone(); iterator.next())
{
System.out.println(iterator.current());
}
System.out.println();
}
private static final class Element{
private Object value;
private Element next; //Referencja do kolejnego obiektu
private Element previous; //Referencja do elementu poprzedniego
public Element(Object value){
setValue(value);
}
public void setValue(Object value) {
this.value = value;
}
public Object getValue() {
return value;
}
//ustawia referencję this.next na obiekt next podany w atgumencie
public void setNext(Element next) {
if (next != null)
this.next = next;
}
public Element getNext(){
return next;
}
public void setPrevious(Element previous) {
if (previous != null)
this.previous = previous;
}
public Element getPrevious() {
return previous;
}
public void wstawPrzed(Element next) {
Element previous = next.getPrevious();
setNext(next);
setPrevious(previous);
next.setPrevious(this);
previous.setNext(this);
}
public void delete() {
previous.setNext(next);
next.setPrevious(previous);
}
}
private class IteratorListowy implements Iterator{
private Element current;
public IteratorListowy() {
current = head;
}
public void next() {
current = current.next;
}
public void previous() {
current = current.previous;
}
public boolean isDone() {
return current == head;
}
public Object current() {
return current.value;
}
public void first() {
current = head.getNext();
}
public void last() {
current = head.getPrevious();
}
}
}
test
public class Program {
public static void main(String[] args) {
Lista lista1 = new Lista();
Lista lista2 = new Lista();
Lista lista3 = new Lista(lista1, lista2);
Student s1 = new Student("Kowalski", 3523);
Student s2 = new Student("Polański", 45612);
Student s3 = new Student("Karzeł", 8795);
Student s4 = new Student("Pałka", 3218);
Student s5 = new Student("Konowałek", 8432);
Student s6 = new Student("Kłopotek", 6743);
Student s7 = new Student("Całka", 14124);
Student s8 = new Student("Pabin", 1258);
Student s9 = new Student("Dryjas", 7896);
Student s10 = new Student("Zając", 5642);
lista1.insert(0, s1);
lista1.insert(0, s2);
lista1.insert(0, s3);
lista1.insert(0, s4);
lista1.insert(0, s5);
lista1.wyswietlListe();
lista1.infoOStanie();
lista2.insert(0, s6);
lista2.insert(0, s7);
lista2.insert(0, s8);
lista2.insert(0, s9);
lista2.insert(0, s10);
lista2.wyswietlListe();
lista2.infoOStanie();
lista3.wyswietlListe();
}
}
As I understood you are trying to concatenate two doubly linked lists list1 and list2, so you would need this simple logic :
// tail of list1 should point to head of list2
lista1.tail.next = lista2.head;
// as we are doubly linked, head of list2 should point back to tail of list1
lista2.head.previous = lista1.tail
this is it, the head of the list1 will now be the head of result list.
Now, doing it in your constructor :
public Lista(Lista lista1, Lista lista2) {
// get hold of lisa1.tail
Element lista1Tail = lista1.getElement(lista1.size() - 1);
listaTail.next = lista2.head;
//now pointer back to tail of lista1
lista2.head.previous = listaTail;
}
This will work, given you fix your getElement() method (which now return not correct index) and add null pointer checks for boundary cases.
As a simpler alternative, I recommend keeping tail member of your list, it is cleaner and more performant.

LinkedList - delete(Object) method works strange - deleting last element doesn't work properly

I have LinkedList with test program. As you can see in that program I add some Students to the list. I can delete them. If I choose s1,s2,s3 oraz s4 to delete everything runs well, and my list is printed properly and information about number of elements is proper. But if I delete last element (in this situation - s5) info about number of elements is still correct, but this element is still printed. Why is that so? Where is my mistake?
public class Lista implements List {
private Element head = new Element(null); //wartownik
private int size;
public Lista(){
clear();
}
public void clear(){
head.setNext(null);
size=0;
}
public void add(Object value){
if (head.getNext()==null) head.setNext(new Element(value));
else {
Element last = head.getNext();
//wyszukiwanie ostatniego elementu
while(last.getNext() != null)
last=last.getNext();
// i ustawianie jego referencji next na nowowstawiany Element
last.setNext(new Element(value));}
++size;
}
public Object get(int index) throws IndexOutOfBoundsException{
if(index<0 || index>size) throw new IndexOutOfBoundsException();
Element particular = head.getNext();
for(int i=0; i <= index; i++)
particular = particular.getNext();
return particular.getValue();
}
public boolean delete(Object o){
if(head.getNext() == null) return false;
if(head.getNext().getValue().equals(o)){
head.setNext(head.getNext().getNext());
size--;
return true;
}
Element delete = head.getNext();
while(delete != null && delete.getNext() != null){
if(delete.getNext().getValue().equals(o)){
delete.setNext(delete.getNext().getNext());
size--;
return true;
}
delete = delete.getNext();
}
return false;
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public IteratorListowy iterator() {
return new IteratorListowy();
}
public void wyswietlListe() {
IteratorListowy iterator = iterator();
for (iterator.first(); !iterator.isDone(); iterator.next())
{
System.out.println(iterator.current());
}
System.out.println();
}
public void infoOStanie() {
if (isEmpty()) {
System.out.println("Lista pusta.");
}
else
{
System.out.println("Lista zawiera " + size() + " elementow.");
}
}
private static final class Element{
private Object value;
private Element next; //Referencja do kolejnego obiektu
public Element(Object value){
setValue(value);
}
public void setValue(Object value) {
this.value = value;
}
public Object getValue() {
return value;
}
//ustawia referencję this.next na obiekt next podany w atgumencie
public void setNext(Element next) {
if (next != null)
this.next = next;
}
public Element getNext(){
return next;
}
}
private class IteratorListowy implements Iterator{
private Element current;
public IteratorListowy() {
current = head;
}
public void next() {
current = current.next;
}
public boolean isDone() {
return current == null;
}
public Object current() {
return current.value;
}
public void first() {
current = head.getNext();
}
}
}
test
public class Program {
public static void main(String[] args) {
Lista lista = new Lista();
Iterator iterator = lista.iterator();
Student s1 = new Student("Kowalski", 3523);
Student s2 = new Student("Polański", 45612);
Student s3 = new Student("Karzeł", 8795);
Student s4 = new Student("Pałka", 3218);
Student s5 = new Student("Konowałek", 8432);
Student s6 = new Student("Kłopotek", 6743);
Student s7 = new Student("Ciołek", 14124);
lista.add(s1);
lista.add(s2);
lista.add(s3);
lista.add(s4);
lista.add(s5);
lista.wyswietlListe();
lista.delete(s5);
lista.wyswietlListe();
lista.infoOStanie();
lista.clear();
lista.infoOStanie();
}
}
The problem is that your setNext(Element next) method does not set anything if next == null. And that is the case for the last element of your list.
So when you call delete.setNext(delete.getNext().getNext());, nothing is actually set because delete.getNext().getNext() is null!
Remove the if (next != null) condition in setNext and it will work.

Categories

Resources