public class LinkedListNode
{
public int info;
public LinkedListNode link;
public LinkedListNode head;
public LinkedListNode()
{
info = 0;
head = null;
link = null;
}
public void insert(int item)
{
LinkedListNode newNode = new LinkedListNode();
LinkedListNode current = head;
if (isEmpty())
{
head = newNode;
newNode.info = item;
newNode.link = head;
}
else
{
while (current.link != head)
{
current = current.link;
}
current.link = newNode;
newNode.info = item;
newNode.link = head;
}
}
public void remove(int item)
{
LinkedListNode current = head;
while ((current.link != head) && (current.link.info != item))
{
current = current.link;
}
if (current.link == head)
System.out.println(item + " is not in the list.");
else
{
current.link = current.link.link;
current = null;
}
}
public boolean isEmpty()
{
return head == null;
}
public void printList()
{
LinkedListNode current = head;
while (current.link != head)
{
System.out.print(current.info + " ");
current = current.link;
}
System.out.print(current.info);
System.out.println();
}
public int getSize()
{
int size = 0;
LinkedListNode current = head;
while (current.link != head)
{
current = current.link;
size += 1;
}
if (current.info != 0)
size += 1;
return size;
}
public void removeThirdItem()
{
LinkedListNode thirdItem = head.link.link.link;
LinkedListNode current = head.link.link;
current.link = thirdItem.link;
thirdItem = null;
}
}
And this is my main program:
public class test
{
public static void main(String[] args)
{
LinkedListNode list = new LinkedListNode();
list.insert(5);
list.insert(14);
list.insert(7);
list.insert(45);
list.insert(21);
System.out.println("Size of list: " + list.getSize());
list.printList();
list.removeThirdItem();
list.printList();
list.removeThirdItem();
list.printList();
list.removeThirdItem();
list.printList();
}
}
The problem is that when I try to remove a third item for the 3rd time, it just keeps printing the linked list, and I have to manually quit the program. Can anyone help me with this? Also, I need some way to remember the position of the node before the node to be removed, so that's were I start counting to another third node, and so on.


Sign In
Create Account


Back to top









