nullpointer exception caused with queue - java

i believe the error is caused by incorrect adding to the queue and there might be other errors but i think it is something here
public void add(E data)
{
if(size == 0)
{
size++;
front = new ListNode(data,null);
}
else
{
size++;
ListNode <E> temp = end;
temp.setNext(null);
temp = temp.getNext();
temp.setData(data);
end = temp;
}
}
if you need the rest of the code to find the error here is the full class
import java.util.*;
public class Queue<E>
{
private ListNode <E> front;
private ListNode <E> end;
private int size;
public Queue()
{
front = null;
end = null;
size = 0;
}
public E peek()
{
return front.getData();
}
public E remove()
{
if(size == 0){return null;}
else
{
ListNode <E> temp = front;
front = temp.getNext();
size--;
return temp.getData();
}
}
public void add(E data)
{
if(size == 0)
{
size++;
front = new ListNode(data,null);
}
else
{
size++;
ListNode <E> temp = end;
temp.setNext(null);
temp = temp.getNext();
temp.setData(data);
end = temp;
}
}
public boolean isEmpty()
{
if (size == 0)
return true;
else
return false;
}
// [data, data, data, data]
public String toString()
{
String s ="";
ListNode <E> temp = front;
while(temp.getNext()!= null)
{
s+=temp.getData() + ", ";
}
return s;
}
public int size()
{
return size;
}
}
and here is the node i'm using
public class ListNode<E>
{
private E data;
private ListNode<E> next;
/**
* Constructs a ListNode with a specified data and next
* #param d the data for the node
* #param n the next reference
*/
public ListNode(E d, ListNode<E> n)
{
data = d;
n = next;
}
/**
* returns the data from the node
* #return the data field
*/
public E getData() {return data;}
/**
* sets the data for the node
* #param d the new data field
*/
public void setData(E d) {data = d;}
/**
* gets the next reference of the node
* #return the next reference
*/
public ListNode<E> getNext() { return next; }
/**
* sets the next reference for the node
* #param n the new next reference
*/
public void setNext(ListNode<E> n) { next = n;}
}
and this is what i am using to test it
public class QueueTester
{
public static void main (String args[])
{
Queue<Integer> queue = new Queue<Integer>();
for (int k = 1; k <= 100; k++) // add 1 to 100
queue.add(k);
System.out.println ("Size: " + queue.size());
System.out.println(queue + "\n");
for (int k = 1; k <= 50; k++) // remove 1 to 50, contents 51 to 100
{
int number = queue.remove();
}
System.out.println ("Size: " + queue.size());
System.out.println(queue + "\n");
for (int k = 200; k <= 500; k+=10) // add tens 200 to 500 (after 51 to 100)
queue.add(k);
System.out.println ("Size: " + queue.size());
System.out.println(queue + "\n");
while (!queue.isEmpty()) // prints contents (should be 51 to 100, then 200 to 500 tens)
{
System.out.print(queue.remove() + " ");
}
System.out.println("\n");
System.out.println ("Size: " + queue.size());
System.out.println(queue); // empty
System.out.println ("Remove from empty queue: " + queue.remove() + "\n") ;
}
}

try this..
if(size == 0)
{
front = new ListNode(data,null);
end = first;
size++;
}
else
{
ListNode <E> temp = new ListNode(data);
end.setNext(temp);
end = end.getNext();
size++;
}

Your add method is not implemented correctly and will always just change the front.
When you call eventually call remove()
public E remove()
{
if(size == 0){return null;}
else
{
ListNode <E> temp = front;
front = temp.getNext();
size--;
return temp.getData();
}
}
since size == 0, you will return null. You then try to dereference null into an int
int number = queue.remove();
This will throw a NullPointerException.
Review your logic, if you add something to the list, you should probably increment the size.
Also, note that in your add() method
ListNode <E> temp = end;
temp.setNext(null);
will also fail since end is originally null.

Related

How can I fix my code to give the correct output instead of giving nothing?

When i run my code, i get nothing as my output. I suspect my code stops on this method:
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
I think it stops at the above method because this code:
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
only returns -1. If i remove the return -1; then Java thinks that there is an error because there is no return statment. I tried adding an else, but i still get the same error.
This is the whole code:
/** The interface for our List (Abstract Data Type) */
interface IList {
/** Adds the given value to the end of the list */
void append(char value);
/** Adds the given value to the beginning of the list */
void prepend(char value);
/** Deletes the container at the given position (a container holds a value) */
void deleteAt(int position);
/** Returns the number of values currently in our list */
int size();
/** Retrieves the value at the given position */
char getValueAt(int position);
/** Searches for the FIRST occurence of a given value in our list.
* If found, it returns the position of that value.
* If not found, it returns -1 */
int positionOf(char value);
}
/** Array implementation of our List */
class ListAsArray implements IList {
// initialize array to a size of 30 elements
// this will prevent the need to resize our array
char[] theArray = new char[30];
public void append(char value)
{
//Count until you find a place in the array that is empty, then insert
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
theArray[i] = value;
}
}
}
public void prepend(char value)
{
//Count until you find a empty value
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
//Once you find the empty value move everything over
for(int j = theArray.length; j != 0; j--)
{
theArray[i] = theArray[i + 1];
}
}
}
//Finally you want to actually add in the number in the first position
theArray[0] = value;
}
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
public int size()
{
//Count until you find a place in the array that is empty, then return the number
int count = 0;
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
return count;
}
count ++;
}
return 0;
}
public char getValueAt(int position)
{
return theArray[position];
}
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
}
/** Singly Linked List implementation of our List */
class ListAsLinkedList implements IList {
//Point to first node and second node
private Node head;
private Node tail;
//Constructor sets head and tail to null
public void LinkedList()
{
head = null;
tail = null;
}
public void append(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
//Set new node to be after current end
tail.setNext(temp);
//Set as new tail
tail = temp;
}
}
public void prepend(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
temp.next = head;
head = temp;
}
}
public void deleteAt(int position)
{
//Make the head node the next node if its the first one
if(position == 0)
{
head=head.next;
}
//If that wasn't the case...
Node current = head;
for(int i = 0; i < position-1; i++)
{
current = current.next;
}
current.next = current.next.next;
if(current.getNext() == null)
{
tail = current;
}
}
public int size()
{
Node temp = head;
for (int i = 0; i != 103; i++)
{
if (temp == tail)
{
return i;
}
}
return 0;
}
public char getValueAt(int position)
{
Node temp=head;
for(int i=0; i < position; i++)
{
temp=temp.next;
}
return temp.data;
}
public int positionOf(char value)
{
//Start at the beginning
int position = 0;
Node current = head;
//Look until we find target data
while (current.getData() != value)
{
//Move to next node
current = current.getNext();
//Increment position
position++;
}
//return position found
return position;
}
}
/** A singly linked list node for our singly linked list */
class Node {
//The node data and link to next node
public char data;
public Node next;
//Constructor
public Node(char data)
{
this.data = data;
this.next = null;
}
//Accessor
public char getData()
{
return data;
}
//Accessor
public Node getNext()
{
return next;
}
//Mutator
public void setData(char data)
{
this.data = data;
}
//Mutator
public void setNext(Node next)
{
this.next = next;
}
}
This is main:
/** contains our entry point */
public class Main {
/** entry point - DO NOT CHANGE the pre-existing code below */
public static void main(String[] args) {
int[] numbers = {105,116,112,115,65,58,47,47,116,105,110,121,88,117,114,108,46,99,111,109,47};
int[] numbers2 = {97,59,111,53,33,111,106,42,50};
int[] numbers3 = {116,104,32,111,116,32,111,71};
/// List as an Array
IList array = new ListAsArray();
// add values
for(int num : numbers) {
array.append((char)num);
}
for(int num : numbers3) {
array.prepend((char)num);
}
// delete some values
int position;
position = array.positionOf((char)105);
array.deleteAt(position);
position = array.positionOf((char)65);
array.deleteAt(position);
position = array.positionOf((char)88);
array.deleteAt(position);
// print em
position = 0;
while (position < array.size()) {
System.out.print(array.getValueAt(position));
position++;
}
/// List as a Linked List
IList linkedList = new ListAsLinkedList();
// add values
for(int num : numbers2) {
linkedList.append((char)num);
}
linkedList.prepend((char)55);
linkedList.prepend((char)121);
// delete some values
position = linkedList.positionOf((char)59);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)33);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)42);
linkedList.deleteAt(position);
// print em
position = 0;
while (position < linkedList.size()) {
System.out.print(linkedList.getValueAt(position));
position++;
}
System.out.println();
// ???
}
}
It should be outputting a link pertaining to the next part of my assignment.
The size() method always returns 0 according to your input.
size() method as per your code doesn't give you the length of the array to iterate over. Therefore you should use array length i.e theArray.length in positionOf() method's for loop instead of size() method.

DoublyLinkedList Issues traveling backwards

I have an assignment to complete a DoublyLinkList assignment and I am having some difficulty with two of the methods. I was given the code for MyList and MyAbstractList and was told to extend MyAbstractList with my DoublyLinkedList. I am not allowed to change MyList or MyAbstractList.
Here is the code for MyList I was provided:
public interface MyList<E extends Comparable<E>> {
/** Return true if this list contains no elements */
public boolean isEmpty();
/** Return the number of elements in this list */
public int size();
/** Add a new element at the proper point */
public void add(E e);
/** Clear the list */
public void clear();
/** Return true if this list contains the element */
public boolean contains(E e);
/** Return the element from this list at the specified index */
public E get(int index);
/** Return the first element in the list */
public E getFirst();
/** Return the last element in the list */
public E getLast();
/** Return the index of the first matching element in this list.
* Return -1 if no match. */
public int indexOf(E e);
/** Return the index of the last matching element in this list
* Return -1 if no match. */
public int lastIndexOf(E e);
/** Remove the first occurrence of the element o from this list.
* Shift any subsequent elements to the left.
* Return true if the element is removed. */
public boolean remove(E e);
/** Remove the element at the specified position in this list
* Shift any subsequent elements to the left.
* Return the element that was removed from the list. */
public boolean remove(int index);
/** Remove the first element in the list, return true if done, false if list is empty */
public boolean removeFirst();
/** Remove the Last element in the list, return true if done, false if list is empty */
public boolean removeLast();
/** Replace the element at the specified position in this list
* with the specified element and return true if done, false if index out of range. */
public boolean set(int index, E e);
}
and this was the code I was provided for MyAbstractList:
public abstract class MyAbstractList<E extends Comparable<E>> implements MyList<E> {
protected int size = 0; // The size of the list
/** Create a default list */
protected MyAbstractList() {
}
/** Create a list from an array of objects */
public MyAbstractList(E[] objects) {
for (int i = 0; i < objects.length; i++)
add(objects[i]);
}
#Override /** Return true if this list contains no elements */
public boolean isEmpty() {
return size == 0;
}
#Override /** Return the number of elements in this list */
public int size() {
return size;
}
}
Finally here is my code for MyDoublyLinkedList:
import java.util.ArrayList;
public class MyDoublyLinkedList<E extends Comparable<E>> extends MyAbstractList<E>
{
int size =0;
Node<E> head = null;
Node<E> current = null;
Node<E> tail = null;
public MyDoublyLinkedList() {
}
/** Create a list from an array of objects */
public MyDoublyLinkedList(E[] objects) {
super(objects);
}
#Override
public boolean isEmpty()
{
return size == 0;
}
#Override
public int size()
{
return size;
}
/** Add a new element at the proper point */
#Override
public void add(E e)
{
Node<E> newNode = new Node<E>(e);
if (tail == null) {
head = tail = newNode;
}
else //if (head != null)
{
tail.next = newNode;
tail = newNode;
}
size++;
}
#Override
public void clear()
{
size = 0;
head = tail = null;
}
#Override
public boolean contains(E e)
{
Node<E> current = head;
for (int i = 0; i < size; i++) {
if (current.element.equals(e))
return true;
current = current.next;
}
return false;
}
#Override
public E get(int index)
{
if (index < 0 || index > size - 1)
return null;
Node<E> current = head;
for (int i = 0; i < index; i++)
current = current.next;
return current.element;
}
#Override
public E getFirst()
{
if (size == 0) {
return null;
}
else {
return head.element;
}
}
#Override
public E getLast()
{
if (size == 0) {
return null;
}
else {
return tail.element;
}
}
#Override
public int indexOf(E e)
{
Node<E> current = head;
for (int i = 0; i < size; i++) {
if (current.element.equals(e))
return i;
current = current.next;
}
return -1;
}
#Override
public int lastIndexOf(E e)
{
int lastIndex = -1;
Node<E> current = head;
for (int i = 0; i < size; i++) {
if (current.element.equals(e))
lastIndex = i;
current = current.next;
}
return lastIndex;
}
/** Remove the first occurrence of the element o from this list.
* Shift any subsequent elements to the left.
* Return true if the element is removed. */
#Override
public boolean remove(E e)
{
int index = indexOf(e);
if (index != -1) {
return remove(index);
} else {
return false;
}
}
/** Remove the element at the specified position in this list
* Shift any subsequent elements to the left.
* Return the element that was removed from the list. */
#Override
public boolean remove(int index)
{
if (index < 0 || index >= size) {
return false;
}
else if (index == 0) {
return removeFirst();
}
else if (index == size - 1) {
return removeLast();
}
else {
Node<E> previous = head;
for (int i = 1; i < index; i++) {
previous = previous.next;
}
Node<E> current = previous.next;
previous.next = current.next;
size--;
return true;
}
}
#Override
public boolean removeFirst()
{
if (size == 0) {
return false;
}
else {
Node<E> temp = head;
head = head.next;
size--;
if (head == null) {
tail = null;
}
return true;
}
}
#Override
public boolean removeLast()
{
if (size == 0) {
return false;
}
else if (size == 1) {
Node<E> temp = head;
head = tail = null;
size = 0;
return true;
}
else {
Node<E> current = head;
for (int i = 0; i < size - 2; i++) {
current = current.next;
}
Node<E> temp = tail;
tail = current;
tail.next = null;
size--;
return true;
}
}
#Override
public boolean set(int index, E e)
{
if (index < 0 || index > size - 1)
return false;
Node<E> current = head;
for (int i = 0; i < index; i++)
current = current.next;
E temp = current.element;
current.element = e;
return true;
}
#Override
public String toString()
{
StringBuilder result = new StringBuilder("[");
Node<E> current = head;
for (int i = 0; i < size; i++) {
result.append(current.element);
current = current.next;
if (current != null) {
result.append(", "); // Separate two elements with a comma
}
else {
result.append("]"); // Insert the closing ] in the string
}
}
return result.toString();
}
public String toStringBack()
{
StringBuilder result = new StringBuilder("[");
Node<E> current = tail;
for (int i = 0; i < size; i++) {
result.append(current.element);
current = current.previous;
if (current != null) {
result.append(", "); // Separate two elements with a comma
}
else {
result.append("]"); // Insert the closing ] in the string
}
}
return result.toString();
}
public void add(int index, E e)
{
if (index ==0) {
addFirst(e);// The new node is the only node in list
}
else if(index > size)
{
addLast(e);//The index location was bigger than size
}
else
{
Node<E> current = getAtIndex(index-1);
Node<E> temp = current.next;
current.next = new Node<E>(e);
(current.next).next = temp;
size++;
}
}
public void addFirst(E e)
{
Node<E> newNode = new Node<E>(e); // Create a new node
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // the new node is the only node in list
tail = head;
}
public void addLast(E e)
{
Node<E> newNode = new Node<E>(e); // Create a new for element e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
}
else {
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++;
}
protected Node<E> getAtIndex(int index)
{
int count;
if (index < 0 || index > size - 1)
return null;
Node<E> temp = null;
if(index <= (size/2))
{
count = -1;
temp = head;
while(++count <= index){
temp = temp.next;
}
}
else if (index > (size/2))
{
count = size;
temp = tail;
while(--count >= index){
temp = temp.previous; //--> this is Where the null pointer exception occurs
}
}
return temp;
}
private static class Node<E>{
E element;
Node<E> next;
Node<E> previous;
public Node(E element){
this.element = element;
next = null;
previous = null;
}
}
}
When I run the add(int index, E e) Method I receive a null pointer exception in the getAtIndext() method. I also have had issues getting the add(E e) Method to add properly when I change the current location. The methods are all as I am being required to use them. The use of iterators while they would be nice are not allowed. I am using Bluj as a compiler. Please let me know what questions you have.
Thank you
EDIT: I do know what a Null Pointer Exception is, I can not figure out why this is coming back as null. The Node "current" should point to the end, then go back in the list until it reaches the indexed location. This only happens when I try to add a node in the last half of the list. The error is thrown at temp = temp.previous;
The stack trace is:
java.lang.NullPointerException at MyDoublyLinkedList.getAtIndex(MyDoublyLinkedList.java:345) at MyDoublyLinkedList.add(MyDoublyLinkedList.java:289) at TestMyDoublyLinkedList.main(TestMyDoublyLinkedList.java:50)
Edit: I figured out the issue. The add() and getAtIndex functions are running properly. When I run the test the function that is throwing a Null Pointer Exception is throwing it at position 8. It cycles through the first few nodes fine, but dies at node 8
When inserting in the add() method, you never assign previous so it is null for all nodes.

Generic Queue, Method to find minimum value

I am implementing a Generic Queue using Linked list. I have the following methods: enqueue, dequeue and peek. I need help with writing a method that will find the minimum value in the queue and throw an exception if the queue is empty.
The code I have so far is:
class Queue <T>
{
private Node front, rear; //begin and end nodes
private int size; // number of items
//nested class to define node
private class Node
{
T item;
Node next;
}
//Zero argument constructor
public Queue()
{
front = null;
rear = null;
size = 0;
}
public boolean isEmpty()
{
return (size == 0);
}
//peek method
public T peek(){
T item = front.item;
return item;
}
//Remove item from the beginning of the list.
public T dequeue()
{
T item = front.item;
front = front.next;
if (isEmpty())
{
rear = null;
}
size--;
return item;
}
//Add T to the end of the list.
public void enqueue(T item)
{
Node oldRear = rear;
rear = new Node();
rear.item = item;
rear.next = null;
if (isEmpty())
{
front = rear;
}
else
{
oldRear.next = rear;
}
size++;
}
public int size()
{
return size;
}
//finds the maximum and minimum in the list
//assumes that head pointer is defined elsewhere
public static void main (String a[])
{
Queue <Integer> q = new Queue<Integer>();
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.enqueue(60);
q.enqueue(70);
System.out.println("Delete an item from queue: " + q.dequeue());
System.out.println("Size of the queue: " + q.size());
System.out.println("Size of the queue: " + q.peek());
}
}
The below method should find the min value and an exception if Queue is empty
I am throwing a custom "QueueEmptyException"
public Integer findMin(Queue q){
if ( q.size == 0 )
throw new QueueEmptyException();
Integer min = q.front.item;
While (q.front.next != null) {
if ( min > q.front.next.item ) {
min = q.front.next.item
q.front = q.front.next;
}
return min;

Copy a single Linked list with parameter (Node <E> node)

The problem I am facing is figuring out how to write a method
public SingleLinkedList copy(Node <E> node) {
}
To return a copy of the list. I have tried:
public SingleLinkedList copy(Node <E> node) {
SingleLinkedList<E> temp = new SingleLinkedList<E>();
Node<E> ref = head;
for(Node<E> n = ref ;ref!= null; n = n.next){
temp.add(n, ref.data);
ref = ref.next;
}
return temp;
}
I created a new list called temp, changed head to ref, iterate through the list and add it to the new list and return the new list, but there's an error with temp.add(n, ref.data).
What am I possibly doing wrong?
class SingleLinkedList<E> {
private static class Node<E> {
private E data;//removed final * private final E data
private Node<E> next;
private Node(E item) {
data = item;
}
}
private Node<E> head;
private int size;
/* Insert item at index, returns true if add is successful. */
public boolean add(int index, E item) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("" + index);
}
if (index == 0) { // adding to the front
Node<E> t = head;
head = new Node<>(item);
head.next = t;
} else { // adding anywhere other than front
Node<E> left = getNode(index - 1);
Node<E> node = new Node(item);
Node<E> right = left.next;
left.next = node;
node.next = right;
}
size++;
return true;
}
/* Add item at end of list, returns true if successful. */
public boolean add(E item) {
return add(size, item);
}
/* Return item at index */
public E get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("" + index);
}
return getNode(index).data;
}
/* Return the number of items */
public int size() {
return size;
}
/* Returns a string representation of the list */
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (Node<E> n = head; n != null; n = n.next) {
sb.append(n.data);
sb.append(" ");
}
sb.append("]");
return sb.toString();
}
/* Return the node at location index */
private Node<E> getNode(int index) {
Node<E> n = head;
for (int i = 0; i < index; i++)
n = n.next;
return n;
}
The problem is you need to pass the position as an int. I also removed the Node n because you do not need it anyways.
I think this should work.
public SingleLinkedList copy() {
SingleLinkedList<E> temp = new SingleLinkedList<E>();
int i = 0;
for(Node<E> ref = head ;ref!= null; ref = ref.next){
temp.add(i++, ref.data);
}
return temp;
}
EDIT: I forgot to drop the parameter you do not need it at all.

How do I remove the first node in a linked list with a remove method

I want to create a linked list then populate it with 1-100. After that I print out all the even numbers without actually removing the odd numbers from the list, then print out the even numbers again, but double them. After these things, I remove the odd numbers from the linked list and print out the list. The last step that I have mentioned is where I am hung up. Everything else works fine, just my remove method removes all the odd numbers except 1. In my main method I use an if statement that says if the number contained in the node % 2 equals zero, remove the node. It works for every node except the first one. Thank you guys for any help you can give me. My code follows.
import java.util.*;
/*
* My ListNode class
*/
class ListNode<Integer> {
private Integer item;
private ListNode<Integer> next;
public ListNode(Integer item) {
this.item = item;
next = null;
}
public ListNode(Integer item, ListNode<Integer> next) {
this.item = item;
this.next = next;
}
public Integer getItem() {
return item;
}
public ListNode<Integer> getNext() {
return next;
}
public void setItem(Integer item) {
this.item = item;
}
public void setNext(ListNode<Integer> next) {
this.next = next;
}
}
/*
* My LinkedList class
*/
class LinkedList<Integer> {
public ListNode<Integer> front;
public LinkedList() {
front = null;
}
public boolean isEmpty() {
return front == null;
}
public boolean contains(int target) {
for (ListNode<Integer> node = front;
node != null;
node = node.getNext()) {
if (node.getItem().equals(target)) {
return true;
}
}
return false;
}
public int size() {
int count = 0;
for (ListNode<Integer> node = front;
node != null;
node = node.getNext()) {
count++;
}
return count;
}
public String toString() {
String result = "( ";
for (ListNode<Integer> node = front;
node != null;
node = node.getNext()) {
result += node.getItem() + " ";
}
return result + ")";
}
public Integer get(int index) {
ListNode<Integer> node = front;
for (int i = 0; i < index; i++) {
node = node.getNext();
}
return node.getItem();
}
public void set(int index, Integer target) {
ListNode<Integer> node = front;
for (int i = 0; i < index; i++) {
node = node.getNext();
}
node.setItem(target);
}
public void add(int index, int target) {
if (isEmpty()) {
front = new ListNode(target);
} else {
ListNode last = front;
while (last.getNext() != null) {
last = last.getNext();
}
last.setNext(new ListNode(target));
}
}
public Integer remove(int index) {
ListNode<Integer> node = front;
ListNode<Integer> prev = front;
for (int i = 0; i < index; i++) {
prev = node;
node = node.getNext();
}
prev.setNext(node.getNext());
return node.getItem();
}
}
public class LinkedListTest {
//interface Removal {
//Integer remove (Integer item);
//}
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
System.out.println(list);
System.out.println("The list size is " + list.size());
System.out.println();
/*
* This adds the numbers 1 through 100 to a LinkedList
*/
for (int i = 1; i <= 100; i++)
list.add(0, i);
System.out.println(list);
System.out.println("The list size is " + list.size());
System.out.println();
/*
* This prints out only even numbers by excluding indexes that are even,
* because all the even numbers are held in the odd numbered indexes, thus
* index 0 is 1 but index 1 is 2, index 3 is 4
*/
for (int i = 0; i < list.size(); i++)
if (i % 2 == 1) {
System.out.print(list.get(i) + " ");
}
System.out.println();
System.out.println("The list size is " + list.size());
System.out.println();
/*
* This doubles even numbers
*/
for (int i = 0; i < list.size(); i++)
if (i % 2 == 1) {
int result = list.get(i) * 2;
System.out.print(result + " ");
}
System.out.println();
System.out.println("The list size is " + list.size());
System.out.println();
for (int i = 0; i < list.size(); i++)
if (list.get(i) % 2 == 1) {
list.remove(i);
}
System.out.print(list);
System.out.println();
System.out.println("The list size is " + list.size());
System.out.println();
/*
* These contain methods only work for the first list created
*/
System.out.println("Does the list contain 32? " + list.contains(32));
System.out.println("Does the list contain 33? " + list.contains(33));
}
}
Your remove method doesn't actually work when value of index is 0.. Because both your node and prev are initialized to front and the loop is not being executed because the i<index condition is false. So you have to add another condition for the case of index=0
Adding these lines at the starting of your remove method solves the problem..
if(index==0){
ListNode<integer>temp=front;
front=front.getNext();
return temp.getItem();
}
hope it helped...

Categories