I am trying to write a program that will delete the nth element from a linked list. Before I was getting a nullpointerexception but I think I cleared that up. Now I just get a repeating error message that I put in the code for when the list goes to the end and is null(error: out of bounds). Can anyone tell me where I went wrong?

import java.util.*;

public class IntNode1
{
 public int item;
 public IntNode1 next;
 public IntNode1 head;

 IntNode1 prev = null;
 IntNode1 curr = head;

 //////Constructor///////
 public IntNode1(int item1, IntNode1 next1)
 {

  head=next1;
  item=item1;
 }

 public void delete_nth(int n)
 {
  
  curr = head;
  while(curr.item != n && n > curr.item)
  {
   if(curr.next==null)
    System.out.println("error: out of bounds");
   else
   {
    prev = curr; //go to next link
    curr = curr.next;
   }
  }
  if(curr == head)
  head = head.next;
  else
  prev.next = curr.next;
   }

 public static void main(String [] args)
 {
  int n;

  //Declare a list
  IntNode1 list1 = new IntNode1(1, new IntNode1(2, new IntNode1(3, new IntNode1
  (4, new IntNode1(5, new IntNode1(6, new IntNode1
  (7, new IntNode1(8, null))))))));

  Scanner sc = new Scanner(System.in);

  System.out.println("number of the element to delete: ");

  n=sc.nextInt();

  list1.delete_nth(n);

  System.out.println(list1);
 }
}

Recommended Answers

All 7 Replies

Before I give you another suggestion for simply fixing one error, I'm curious to know what kind of Linked List you want to make?

It looks like you want to make a doubly linked list, but I could be wrong. It also seems that you may, instead, be making a circular linked list where each node has quick access to the root node. Are either of these scenarios correct?

I need to make a linked with the integers 0-8, so Im pretty sure that it needs to be cicular. Im actually missing the 0 int in the list that I built in the main method(just put it in), but it doesnt seem to solve anything.

ok, so it is a singly linked list where the node consists of a part to store the element and a link to the next node

ok, so it is a singly linked list where the node consists of a part to store the element and a link to the next node

If it's just a singly linked list, you only need a reference to the next node.

I'm going to give you some code I wrote in a class awhile back. It may or may not help you but I think it just might--

/**
List class
[print()] toString()
[insertAtBack()] setLastNode(String someWord, int someNum)
[insertAtIndex()] insertAtPoint(String someWord, int someNum, int x)
[findElementBeforeXIndex()] theElementBeforeX(int x)
*/

public class List<PARAMETER>
{
	private Node firstNode;
//	private Node tempNode, tempNode2, tempNode3;

/**
Determine whether the list is empty
*/
	public boolean isEmpty()
	{
		return firstNode == null;
	}//end isEmpty

/**
Removes the first node in the list
*/
	public boolean deleteFirstNode()
	{
		if(firstNode != null)
		{
			firstNode = firstNode.getNext();
			return true;
		}//end if
		else
			return false;
	}//end deleteFirstNode

/**
To call the element before the x element
Elements are in order 0, 1, 2, 3..., listSize() - 1.
*/
	private Node theElementBeforeX(int x)
	{
		if(x > listSize() || x < 0)
		{
			System.out.println("Null pointer error");
			return null;
		}//end if

		int i = 0;
		Node position = firstNode;

		if(x == 0)
		{
			System.out.println("No element before 0th");
			return position;
		}//end if

		while(i < (x - 1))
		{
			position = position.getNext();
			i++;
		}//end while

		return position;
	}//end theElementBeforeX

/**
Returns the size of the list
*/
	public int listSize()
	{
		int count = 0;
		Node position = firstNode;

		while(position != null)
		{
			count++;
			position = position.getNext();
		}//end while

		return count;
	}//end listSize

/**
Method for locating a String value in the list
*/
	public boolean contains(String aString)
	{
		return(find(aString) != null);
	}//end contains

/**
Method for finding a String target
*/
	private Node find(String target)
	{
		Node position = firstNode;
		String itemAtPosition;
		while(position != null)
		{
			itemAtPosition = position.getItem();
			if(itemAtPosition.equals(target))
				return position;
			position = position.getNext();
		}//end while

		return null;
	}//end find

/**
Sets the element at the last position of the List
*/
	public void setLastNode(String someWord, int someNum)
	{
			Node position = firstNode;
			int b = listSize();
			Node lastNode = null;
			lastNode = new Node(someWord, someNum, lastNode);
			boolean continuim = true;

			if(position != null)
			{
				while(b != 0)
				{
					position = theElementBeforeX(b);
					lastNode = new Node(position.getItem(), position.getData(), lastNode);
					b--;
				}//end while
			}//end if

			firstNode = lastNode;
	}//end

/**
Enables the user to place elements in the linkList at a specified "x" point
Points in the linkList range from 0, 1, 2, 3... , listSize() - 1.
*/
	public void insertAtPoint(String someWord, int someNum, int x)
	{
		//firstNode is allocated to 2 different places in memory
			Node position = firstNode;
			Node secondPosition = null;
			secondPosition = firstNode;
			int b = listSize();

			boolean continuim = true;
			Node indexNode = null;

			if(x < 0 || x > (listSize() - 1))
			{
				System.out.println("Null pointer error, canceling method");
				return;
			}//end if
			else if(x == 0)
			{
				insertAtFront(someWord, someNum);
				return;
			}//end else if
			else if(x == (listSize() - 1))
			{
				setLastNode(someWord, someNum);
				return;
			}//end else if
			else if(x > 0 && x < (listSize() - 1))
			{
				indexNode = new Node(someWord, someNum, indexNode);
			}//end else if

			if(position != null)
			{
				//Sets nodes from the original link to the front of the new node
				for(int i = x; i > 0; i--)
				{
					position = theElementBeforeX(i);
					indexNode = new Node(position.getItem(), position.getData(), indexNode);
				}//end while

				//Necessary to change the private instance Node to the values set before indexNode
				firstNode = indexNode;

				//Sets the second position to the xth element of the initial copy of the linkList
				for(int j = 0; j < x; j++)
				{
					secondPosition = secondPosition.getNext();
				}//end for

				//Sets the end values of the new linkList from the initial linkList
				while(secondPosition != null)
				{
					setLastNode(secondPosition.getItem(), secondPosition.getData());
					secondPosition = secondPosition.getNext();
				}//end while
			}//end if
	}//end insertAtPoint

/**
Enables the user to place elements in the linkList at a specified "x" point
Points in the linkList range from 0, 1, 2, 3... , listSize() - 1.
*/
	public void anotherInsertAtPointMethodX(String someName, int someNum, int x)
	{
		//This is finding the lin previous ot where we want to insert
		Node previous = theElementBeforeX(x);

		Node addNode = new Node(someName, someNum, previous.getNext());

		previous.setNext(addNode);
	}

/**
Insert a new node at beginning of list
*/
	public void insertAtFront(String itemName, int val)
	{
		firstNode = new Node(itemName, val, firstNode);
	}//end insertAtFront

/**
Prints out the elements in the list and their memory locations
*/
	public String toString()
	{
		Node position = firstNode;

		while(position != null)
		{
			System.out.println(position.getItem() + " " + position.getData());
			System.out.println(position);
			position = position.getNext();
		}//end while
		return "\n^^The current list.";
	}//end toString


/**
Inner class Node that calls itself at its current state, and places
elements on top of the first element
*/

	private class Node
	{
		private int data;
		private Node link;
		private String item;

		//create a node with data and a link
		public Node(String newItem, int dat, Node ref)
		{
			setData(newItem, dat);
			link = ref;
		}//end constructor

		public Node(int dat)
		{
			this("not null", dat, null);
		}//end second constructor

		public void setData(String newItem, int x)
		{
			item = newItem;
			data = x;
		}//end setData

		public int getData()
		{
			return data;
		}//end getData

		public void setNext(Node next)
		{
			link = next;
		}//end setLink

		public Node getNext()
		{
			return link;
		}//end getLink

		public String getItem()
		{
			return item;
		}

	}//end private inner class

}//end class

Ignore the Parameter statement above. When I wrote this I wasn't used to using Generics, so I left it out (fairly certain). Ignore some of the comments too please (just looked at the node class one and kinda laughed...).

I don't like recreating the wheel when I already have one. If this isn't enough I can provide an example of a Linked list built from scratch.

-Alex

I just rewrote using a for loop this time and when I run the program I get IntNode1@1d31859, which I think corresponds to that elements address in memory?

import java.util.*;

public class IntNode1
{
 public int item;
 public IntNode1 next;
 public IntNode1 head;

 //////Constructor///////
 public IntNode1(int item1, IntNode1 next1)
 {

  next=next1;
  item=item1;
 }

 public void delete_nth(int n)
 {
 IntNode1 prev = null;
 IntNode1 curr = head;

  curr = head;
  
  for(curr=head; curr!=null; prev=curr, curr=curr.next)
  {
    if(curr.item == n)
    {
      if(prev==null){
        head = curr.next;
      }else
      {
        prev.next=curr.next;
      }
    }
  }
 }
  
 public static void main(String [] args)
 {
  int n;

  //Declare a list
  IntNode1 list1 = new IntNode1(0, new IntNode1(1, new IntNode1(2, new IntNode1(3, new IntNode1
  (4, new IntNode1(5, new IntNode1(6, new IntNode1
  (7, new IntNode1(8, null)))))))));

  Scanner sc = new Scanner(System.in);

  System.out.println("number of the element to delete: ");

  n=sc.nextInt();

  list1.delete_nth(n);

  System.out.println(list1);
 }
}

That is correct.

Do you think it would be more beneficial for me to explain to you how a linked list works?

no, I get how the linked list works, there are 2 parts to every node containing an element and the address to the next node, so if you have the address to the first node you can access every node in the list. With the deletion I basically just trying to bypass a node by getting the previous node to point past the node I want deleted and have it point to the next node in the list. I think this is correct. Its all still new to me so still trying to polish it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.