LinkedList NullPointerException? - java

Hey I can't seem to get my code to work, there is something wrong with the constructor and I just can't figure out what it is.
I had it working for the constructor and tried it for some of the methods but even then it still gave me NullPointerException
import java.util.NoSuchElementException;
public class LinkedString
{
//Required Nodes/counters to track positions in LinkedList
private Node start;
private Node end;
private int counter;
private int i = 0;
//Inner class Node provides the node object required to create links
private class Node
{
public char data;
public Node next;
}
//This constructor allows the user to input a array of characters
//and have them created into a LinkedString object
public LinkedString(char[] value)
{
start.data = value[0];
counter = 0;
for(int i = 0 ; i < value.length ; i++)
{
if ( start == null)
{
start.data = value[i];
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data = value[i];
end.next = newNode;
newNode.next = null;
end = newNode;
counter++;
}
}
}
//This constructor allows the user to input a String
//getting each character and creating it into a LinkedString object
public LinkedString(String value)
{
counter=0;
for(int i = 0; i < value.length(); i++)
{
if(start == null)
{
start.data = value.charAt(i);
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data=value.charAt(i);
end.next = newNode;
newNode.next = null;
end = newNode;
}
}
}
//This accessor returns a value at the specified index
//The 1st character has an index of 0 and will throw
//a no such element exception if there is no char # given index
public char charAt(int index)
{
Node current = start;
boolean found = false;
char temp = 0;
int i = 0;
while (current.next != null && i <= index)
{
current = current.next;
if(i == index)
{
found = true;
//Return done, and Data is wrong Edit.
}
i++;
temp = current.data;
}
if(found == false) {
throw new NoSuchElementException();
}
return temp;
}
//concat connects two linkedString objects together and updates the
//counter for how many chars are in the combined list
public LinkedString concat(LinkedString value)
{
end.next = value.start;
end = value.end;
counter = counter + value.length();
return value;
}
//isEmpty checks to see if the list has a initial value
//if it doesnt its empty and returns true
public boolean isEmpty()
{
if(start == null)
{
return true;
}
else
{
return false;
}
}
//length() returns the counter variable which counts the number of
// characters in the linked string
public int length()
{
return counter;
}
//substring returns a copy of the linked string from a specified point
//to another, if the user attempts to copy a value from a not existing
//index point it throws NoSuchElementException
public Node substring(int startIndex, int endIndex)
{
Node current = start;
Node sIndex;
Node eIndex;
Node copy = null;
int i = 0;
while(current.next != null && i <= startIndex)
{
current = current.next;
if(i == startIndex)
{
sIndex = current;
sIndex.next = copy;
while(current.next != null && i <= endIndex)
{
current = current.next;
copy.next = current;
copy = current;
if(i == endIndex)
{
eIndex = current;
eIndex.next = null;
copy.next = eIndex;
}
i++;
}
if(i < endIndex)
throw new NoSuchElementException();
}
i++;
}
return copy;
}
}
public class LinkedStringMain {
public static void main(String[] args) {
LinkedString linked = new LinkedString("stack");
System.out.println(" " + linked.charAt(0));
System.out.println(" " + linked.isEmpty());
}
}

The error is that start is not being initialized in your either of your constructors after you check if it is null. To fix this, initialize start using start = new Node();. The changes are implemented below:
//This constructor allows the user to input a array of characters
//and have them created into a LinkedString object
public LinkedString(char[] value)
{
start.data = value[0];
counter = 0;
for(int i = 0 ; i < value.length ; i++)
{
if ( start == null)
{
start = new Node(); //initialize start
start.data = value[i];
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data = value[i];
end.next = newNode;
newNode.next = null;
end = newNode;
counter++;
}
}
}
//This constructor allows the user to input a String
//getting each character and creating it into a LinkedString object
public LinkedString(String value)
{
counter=0;
for(int i = 0; i < value.length(); i++)
{
if(start == null)
{
start = new Node(); //initialize start
start.data = value.charAt(i);
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data=value.charAt(i);
end.next = newNode;
newNode.next = null;
end = newNode;
}
}
}

Related

How to reverse a LinkedList from a certain index, given the code fragments below

I would like to write a method public void reverseFrom(int index) which reverses a list from the given index.
I would like to only use the LinkedList class below.
public class LinkedList {
public Node head = null;
public class Node {
public int value;
public Node next;
Node(int value, Node next) {
this.value = value
this.next = next;
}
}
}
I have a method to reverse a LinkedList:
public void reverse() {
Node tmp = head;
Node prev = null;
Node nextNode = null;
while(tmp != null) {
nextNode = tmp.next;
tmp.next = prev;
prev = tmp;
tmp = nextNode;
}
head = prev;
}
So far, for the reverseFrom method, I have:
public void reverseFrom(int index) {
if(index == 0) {
reverse();
} else if (index == 1) {
return;
} else {
Node tmp = head;
for(int i = 0; i < index; i++) {
tmp = tmp.next;
}
Node newHead = tmp;
/*** Node prev = null;
Node nextNode = null;
while(newHead != null) {
nextNode = newHead.next;
newHead.next = prev;
prev = newHead;
newHead = nextNode;
}
newHead = prev; ***/
}
}
I have tried using the code from reverse() but it does not work (that which is commented out).
How can I then reverse the list from newHead?
You could base the logic on the reverse method, but use an extra reference to the node that is at index - 1. During the loop decrement index. As long as it is positive, don't change the next reference of the current node. When it hits zero, take note of where we start the reversal, and as the current node will become the very last one, set its next reference to null. When index is negative, perform the usual reversal logic.
After the loop, check whether we need to change the head or whether we need to attach the reversed part to the node at index-1:
public void reverseFrom(int index) {
Node tmp = head;
Node prev = null;
Node nextNode = null;
Node tail = null; // node at index - 1
while (tmp != null) {
nextNode = tmp.next;
if (index == 0) {
// We arrived at the part that needs reversal
tmp.next = null;
tail = prev;
} else if (index < 0) {
// Perform normal reversal logic
tmp.next = prev;
}
index--;
prev = tmp;
tmp = nextNode;
}
if (tail == null) {
head = prev;
} else {
tail.next = prev;
}
}
public class ReverseList<T> extends LinkedList<T>{
public void reverseFrom(int idx) {
if (idx < 0 || idx > size()) {
return;
}
Stack<T> stack = new Stack<T>();
while (idx < size()) {
stack.push(remove(idx));
}
while (!stack.isEmpty()) {
add(stack.pop());
}
}
/******* Alternative slution ***************/
public void reverseFrom(int idx) {
if (idx < 0 || idx > size()) {
return;
}
reverseFromInternal(idx, size()-1);
}
private void reverseFromInternal(int a, int b) {
if (a >= b) {
return;
}
T far = remove(b);
T near = remove(a);
add(a, far);
add(b, near);
reverseFromInternal(a + 1, b - 1);
}
/****************************************/
public static void main(String [] args) {
ReverseList<String> list = new ReverseList<>();
for (int i = 0; i < 10; i++) {
list.add(Integer.toString(i));
}
list.reverseFrom(5);
System.out.println(list);
}
}
public void reverseFrom(int index) {
if (index == 0) {
reverse();
return;
}
Node tmp = head;
Node previous = null;
for (int i = 0; i < index; i++) {
previous = tmp;
tmp = tmp.next;
}
Node newHead = tmp;
LinkedList subLinkedList = new LinkedList();
subLinkedList.head = newHead;
subLinkedList.reverse();
previous.next = subLinkedList.head;
}

How to write an add/insert method with a DoublyLinkedList in Java

I need help with my add method in java. It works with DoublyLinked List.
I am implementing a cyclic DoublyLinkedList data structure. Like a singly
linked list, nodes in a doubly linked list have a reference to the next node, but unlike a singly linked list, nodes in a doubly linked list also have a reference to the previous node. Additionally, because the list is "cyclic", the "next" reference in the last node in the list points to the first node in the list, and the "prev" reference in the first node in the list points to the last node in the list.
What the method is suppose to do is insert the value parameter at the specified index in the list. Be sure to address the case in which the list
is empty and/or the added element is the first in the list. If the index parameter is invalid, an IndexOutOfBoundsException should be thrown.
Here is my code below:
public class DoublyLinkedList<E>
{
private Node first;
private int size;
#SuppressWarnings("unchecked")
public void add(E value)
{
if (first == null)
{
first = new Node(value, null, null);
first.next = first;
first.prev = first;
}
else
{
first.prev.next = new Node(value, first, first.prev);
first.prev = first.prev.next;
}
size++;
}
private class Node<E>
{
private E data;
private Node next;
private Node prev;
public Node(E data, Node next, Node prev)
{
this.data = data;
this.next = next;
this.prev = prev;
}
}
Here is the method where it fails. I will comment the line where I'm stuck on, but other than that, what is done in the previous lines is correct from what I heard.
#SuppressWarnings("unchecked")
public void add(int index, E value)
{
if(index < 0)
{
throw new IndexOutOfBoundsException();
}
if(index > size)
{
throw new IndexOutOfBoundsException();
}
if (first.data == null)
{
throw new NullPointerException();
}
if (index == 0)
{
first = new Node(value, null, null);
first.next = first;
first.prev = first;
}
else
{
Node current = first;
for (int i = 0; i < index; i++)
{
current = current.next;
}
current.prev.next = new Node(value, current, current.prev); // This is the line where I get lost on.
current.prev = current.prev.next;
}
size++;
}
The rest of my code is here. Please focus on the method I'm working on. thank you!
#SuppressWarnings("unchecked")
public void remove(int index)
{
if(index < 0)
{
throw new IndexOutOfBoundsException();
}
if(index > size)
{
throw new IndexOutOfBoundsException();
}
if (first.data == null)
{
throw new IndexOutOfBoundsException();
}
else if (index == 0)
{
first = first.next;
}
else
{
Node current = first.next;
for (int i = 0; i < index; i++)
{
current = current.next;
}
// current.prev = current.next;
current.next = current.next.next;
}
size--;
}
#SuppressWarnings("unchecked")
public E get(int index)
{
if(index < 0)
{
throw new IndexOutOfBoundsException();
}
if(index > size)
{
throw new IndexOutOfBoundsException();
}
Node current = first;
for (int i = 0; i < index; i++)
{
current = current.next;
}
return (E) current.data;
}
#SuppressWarnings("unchecked")
public int indexOf(E value)
{
int index = 0;
Node current = first;
while (current != current.next)
{
if (current.data.equals(value))
{
return index;
}
index++;
current = current.next;
}
return index;
}
public boolean isEmpty()
{
if (size == 0)
{
return true;
}
else
{
return false;
}
}
public int size()
{
return size;
}
#SuppressWarnings("unchecked")
public String toString()
{
if (isEmpty())
{
return "[]";
}
else
{
String result = "[" + first.data;
Node current = first.next;
for(int i = 0; i < size-1; i++)
{
result += ", " + current.data;
current = current.next;
}
result += "]";
return result;
}
}
}
This was not easy at all, however I figured out the answer to my question.
#SuppressWarnings("unchecked")
public void add(int index, E value)
{
if(index > size || index < 0)
{
throw new IndexOutOfBoundsException();
}
if (first == null)
{
Node n = new Node(value, null, null);
n.next = n;
n.prev = n;
first = n;
}
else
{
Node current = first;
for (int i = 0; i < index; i++)
{
current = current.next;
}
//current points to node that will follow new node.
Node n2 = new Node(value, current, current.prev);
current.prev.next = n2;
current.prev = n2;
//update first if necessary.
if(index == 0)
{
first = n2;
}
}
size++;
}

Trouble creating append method to assist in replacing substrings in LinkedList

I have the methods replace() and append() to allow the replace method to replace the characters of a sub-string "LString" with the characters in "lStr" in a Linked List class LString. However im having trouble resolving my append methods in my replace class.
It may be because im not providing a node constructor with a LString parameter. Im not certain how to correct the issue. The relevant methods are at the very bottom of my class.
public class LString {
node front;
node end;
int length;
LString next;
char letter;
// create node class
public class node {
char data;
node next;
public node(LString newData) {
LString data;
}
public node(char newData, node newNext) {
data = newData;
next = newNext;
}
}
// LString constructor
// constructs LString object representing empty list of chars
public LString() {
this.length = 0;
this.front = null;
}
// Construct LString copy of original parameter
public LString(String original) {
//assign first char to front
node curr = this.front;
this.length = original.length();
// loop through
for (int i = 0; i < original.length(); i++) {
if (i == 0) {
front = new node(original.charAt(i), null);
curr = front;
} else {
curr.next = new node(original.charAt(i), null);
curr = curr.next;
}
}
}
// return length in this LString
// can use in LString constructor
public int length() {
return this.length;
}
//create and return string with contents of LString
public String toString() {
// use string builder to meet time limit
StringBuilder builder = new StringBuilder();
if (front == null) {
return "";
} else {
node curr = front;
while (curr != null) {
builder.append(curr.data);
curr = curr.next;
}
return builder.toString();
}
}
//compares string lists 0 if equal -1 if less, and 1 if greater
public int compareTo(LString anotherLString) {
//save lowest length of strings
int minLength;
// get front spots
node curr = this.front;
node otherCurr = anotherLString.front;
// get lengths
int thisString = length();
int otherString = anotherLString.length();
// get shortest length of 2 strings
if (thisString < otherString) {
minLength = thisString;
} else {
minLength = otherString;
}
//go through characters in each string and compare for lexicographic order
int iterate = 0;
while (iterate < minLength) {
char string1Char = curr.data;
char string2Char = otherCurr.data;
if (string1Char != string2Char) {
return string1Char - string2Char;
}
iterate++;
curr = curr.next;
otherCurr = otherCurr.next;
}
return thisString - otherString;
}
//Return true if LString represents the same list of characters as other
#Override
public boolean equals(Object other) {
if (other == null || !(other instanceof LString))
return false;
else {
// use compareTo to determine if strings are the same
LString otherLString = (LString) other;
if (compareTo(otherLString) == 0) {
return true;
} else {
return false;
}
}
}
//Return the char at the given index in this LString.
public char charAt(int index) {
int length = this.length();
// check for index out of bounds
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException();
}
// returns char at index
node curr = front;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
return curr.data;
}
//Set the char at the given index in this LString to ch.
public void setCharAt(int index, char ch) {
// check for index out of bounds
int length = this.length();
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException();
}
// replaces char at index
node curr = front;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
curr.next = new node(curr.data, curr.next);
curr.data = ch;
}
//Returns a new LString that is a sub-string of this LString.
public LString substring(int start, int end) {
LString newLString = new LString();
// handle exceptions
if (start < 0 || start > end) {
throw new IndexOutOfBoundsException();
} else if (end > this.length()) {
throw new IndexOutOfBoundsException();
//return null in special case (empty LString)
} else if (start == end) {
//&& end == this.length()
return newLString;
} else {
node node = this.front;
for (int i = 0; i < start; i++) {
node = node.next;
// insert substring
}
node copy = new node(node.data);
newLString.front = copy;
for (int i = start + 1; i < end; i++) {
node = node.next;
copy = copy.next = new node(node.data);
}
return newLString;
}
}
// Replaces this characters in a sub-string of this LString with the characters in lStr.
public LString replace(int start, int end, LString lStr) {
// handle exceptions
if (start < 0 || start > end) {
throw new IndexOutOfBoundsException();
} else if (end > this.length()) {
throw new IndexOutOfBoundsException();
}
LString replacedLs = new LString();
replacedLs.append(substring(0, start));
replacedLs.append(lStr);
replacedLs.append(substring(end, this.length));
return replacedLs;
}
//append helper method
public void append(LString data) {
this.length++;
if (front == null) {
front = new node(data);
return;
}
node curr = front;
while (curr.next != null) {
curr = curr.next;
}
curr.next = new node(data);
}
}
I appreciate any help, thank you.
Look at your node constructor, it simply does nothing:
public node(LString newData) {
LString data;
}
to make it work you should assign all LString.front fields to the current object, so:
public node(LString newData) {
this.data = newData.front.data;
this.next = newData.front.next;
}

Erorr with the nullpointer

public class List {
private class Node {
public Node next = null;
Object element;
Node text;
Node(Object element, Node prevNode) {
this.element = element;
prevNode = this;
}
Node(Object element) {
this.element = element;
element = null;
}
}
private Node head;
private Node tail;
private int count;
public List() {
this.head = null;
this.tail = null;
this.count = 0;
}
public void add(Object item) {
if (head == null) {
// We have empty list
head = new Node(item);
tail = head;
} else {
// We have non-empty list
Node newNode = new Node(item, tail);
tail = newNode;
}
count++;
}
public Object remove(int index) {
if (index >= count || index < 0) {
throw new IndexOutOfBoundsException("Invalid index: " + index);
}
// Find the element at the specified index
int currentIndex = 0;
Node currentNode = head;
Node prevNode = null;
while (currentIndex < index) {
prevNode = currentNode;
currentNode = currentNode.next;
currentIndex++;
count--;
if (count == 0) {
head = null;
tail = null;
} else if (prevNode == null) {
head = currentNode.next;
} else {
prevNode.next = currentNode.next;
}
}
return currentNode.element;
}
public int remove(Object item) {
// Find the element containing searched item
int currentIndex = 0;
Node currentNode = head;
Node prevNode = null;
while (currentNode != null) {
if ((currentNode.element != null && currentNode.element
.equals(item))
|| (currentNode.element == null)
&& (item == null)) {
break;
}
prevNode = currentNode;
currentNode = currentNode.next;
currentIndex++;
}
if (currentNode != null) {
// Element is found in the list. Remove it
count--;
if (count == 0) {
head = null;
tail = null;
} else if (prevNode == null) {
head = currentNode.next;
} else {
prevNode.next = currentNode.next;
}
return currentIndex;
} else {
// Element is not found in the list
return -1;
}
}
public int indexOf(Object item) {
int index = 0;
Node current = head;
while (current != null) {
if ((current.element != null && current.element.equals(item))
|| (current.element == null) && (item == null)) {
return index;
}
current = current.next;
index++;
}
return -1;
}
public boolean contains(Object item) {
int index = indexOf(item);
boolean found = (index != -1);
return found;
}
public Object elementAt(int index) {
if (index >= count || index < 0) {
throw new IndexOutOfBoundsException("Invalid index: " + index);
}
Node currentNode = this.head;
for (int i = 0; i < index; i++) {
currentNode = currentNode.next;
}
return currentNode.element;
}
public int getLength() {
return count;
}
public static void main(String[] args) throws NullPointerException {
List shoppingList = new List();
shoppingList.add("Milk");
shoppingList.add("Honey");
shoppingList.add("Olives");
shoppingList.add("Beer");
shoppingList.remove("Olives");
System.out.println("We need to buy:");
for (int i = 0; i < shoppingList.getLength(); i++) {
System.out.println(shoppingList.elementAt(i));
}
System.out.println("Do we have to buy Bread? "
+ shoppingList.contains("Bread"));
}
}
Its giving me that in maina and index of have nullpointer.
Where is my mistake ?
And i want to know how to fix this problem. Thank you.
I would be very grateful if you could give me some feedback for code.
You do not set next when you create your Nodes, so next is always null.
This
Node(final Object element, Node prevNode) {
this.element = element;
prevNode = this;
}
should be
Node(final Object element, Node prevNode) {
this.element = element;
prevNode.next = this;
}
I understand there's something in your code that's giving you nullpointerException when you run the program, but there's no need of it being in the main method, any method called by main may be giving the exception. Still, try this:
Replace this line:
for (int i=0; i<shoppingList.getLength(); i++) {
by this one:
for (int i=0; i < shoppingList.length(); i++) {
if .length() doesn't work, maybe .size() will do.
for (int i=0; i<shoppingList.size(); i++) {
If you are using eclipse, netbeans or any other environment, post which line is throwing the NullPointerException. We can't help you unless you give us more data.

Having some trouble using a Linked List and passing elements to the Node

In this specific instance, it takes into account two occasions. One where I'm trying to place a node in the beginning of the Linked List and one where I'm trying to place it in the middle or at the end. Here is my Node Class. If you look at my INSERT method, the part that is not working is:
Node newNode = new Node();
newNode.setExponent(element);
class Node {
private int coefficient;
private int exponent;
private Node link;
// Constructor: Node()
Node(int c, int e) {
// Sets coefficient to c, exponent to e, and link to null
coefficient = c;
exponent = e;
link = null;
}
// Inspectors: getCoefficient(), getExponent(), getLink()
public int getCoefficient() {
// Returns coefficient
return coefficient;
}
public int getExponent() {
// Returns exponent
return exponent;
}
public Node getLink() {
// Returns link
return link;
}
// Modifiers: setCoefficient(), setExponent(), setLink()
public void setCoefficient(int c) {
// Sets coefficient to c
coefficient = c;
}
public void setExponent(int e) {
// Sets exponent to e
exponent = e;
}
public void setLink(Node n) {
// Sets link to n
link = n;
}
}// Ends Node Class
Here is where I'm trying to insert to my Linked List along with some other methods in the class that should help give you an idea of how my code looks.
class List {
private Node head; // Points to first element of the list
private int count; // number of elements in the list
// Constructor:
List() {
// Sets head to null and count to zero
head = null;
count = 0;
}
// Inspectors:
// Returns the number of elements in the list
public int size() {
return count;
}
// Modifiers:
// Inserts element at index in the list. Returns true if successful
public boolean insert(int index, Node element) {
if (index < 0 || index > count)return false;
if (index == 0) {
Node newNode = new Node();
newNode.setExponent(element);
count++;
newNode.setLink(head);
head = newNode;
return true;
}
Node walker = head;
for (int i = 1; i < (index - 1); i++)
walker = walker.getLink();
Node newNode = new Node();
newNode.setExponent(element);
newNode.setLink(walker.getLink());
walker.setLink(newNode);
count++;
return true;
}
Try this:
Assumption: You are trying to insert a Node element into the index of LinkedList
Your insert method with modification.
public boolean insert(int index, Node element) {
//if (index < 0 || index > count)
if (index < 0 || index > count + 1) return false;
if(head == null) {
head = element;
return true;
}
if (index == 0) {
//Node newNode = new Node();
//newNode.setExponent(element);
count++;
element.setLink(head);
//newNode.setLink(head);
head = element;
//head = newNode;
return true;
}
Node walker = head;
//for (int i = 0; i < (index - 1); i++)
for (int i = 1; i < index; i++) {
walker = walker.getLink();
}
//Node newNode = new Node();
//newNode.setExponent(element);
element.setLink(walker.getLink());
//newNode.setLink(walker.getLink());
//walker.setLink(newNode);
walker.setLink(element);
count++;
return true;
}
Sample Test Case:
print method:
void print() {
Node travel = head;
while(travel!= null) {
System.out.println(travel.getExponent() + " " + travel.getCoefficient());
travel = travel.getLink();
}
}
Main method:
public static void main(String args[]) {
Node n1 = new Node(1,2);
List l = new List();
l.insert(0,n1);
Node n2 = new Node(3,2);
l.insert(1,n2);
Node n3 = new Node(4,5);
l.insert(0,n3);
l.print();
}

Categories