deepak-malik/Data-Structures-In-Java

problem with the size when trying to delete items

simohamedhdafa opened this issue · 3 comments

`package com.deepak.data.structures.LinkedList;

public class theGame {

public static void main(String[] args) {
	
	CircularLinkedList<Integer> g = new CircularLinkedList<Integer>();
	int [] t = {15, 14, -12, 7, -7, 20, 13, 1, -15, -14, 12, 71, -17, -20, 103, 10};
	for(int e : t) g.insertAtTail(e);
	g.display();
	int i = 0; 
	while(g.size()>1) g.deleteFromPosition((i++)%g.size());
	System.out.println("Winner:");
	g.display();
}

}`

Thanks for finding this issue. Can you please explain a bit more what is happening when you try to delete items? Is there any exception? Also if you can raise a pull request for the issue, that will be great.

My pleasure. As I wanted to show with the code above, when I try to delete all the items, except a last one from the CircularLinkedList g that I created, the g.size() returns an incorrect answer. To be sure, I display the list and there are already items there ! You can execute the main method to get a better understanding of the issue. If there is a chance I may not have fully understood the use of your CircularLinkedList class, please let me know where I missed it.

I found the issue. In the method deleteFromPosition( ) the size decrementation should be written in the else bloc, like this :

public void deleteFromPosition(int position) {
		if (position < 0 || position >= size) {
			throw new IllegalArgumentException("Position is Invalid");
		}
		Node<E> current = head, previous = head;
		for (int i = 0; i < position; i++) {
			if (current.next == head) {
				break;
			}
			previous = current;
			current = current.next;
		}
		if (position == 0) {
			deleteFromBeginning();
		} else {
			previous.next = current.next;
			size--;
		}
	}