Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

problem with the size when trying to delete items #1

Open
simohamedhdafa opened this issue May 1, 2019 · 3 comments
Open

problem with the size when trying to delete items #1

simohamedhdafa opened this issue May 1, 2019 · 3 comments

Comments

@simohamedhdafa
Copy link

simohamedhdafa commented May 1, 2019

`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();
}

}`

@deepak-malik
Copy link
Owner

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.

@simohamedhdafa
Copy link
Author

simohamedhdafa commented May 1, 2019

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.

@simohamedhdafa
Copy link
Author

simohamedhdafa commented May 1, 2019

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--;
		}
	}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants