I think that smallIndex, index, and temp all have values, so Im not sure why I am getting the error. Can anyone explain to me why this is happening? The error message is:
Exception in thread "main" java.lang.NullPointerException
public class LinkedList
{
public class LinkedListNode
{
public int info;
public LinkedListNode next;
public LinkedListNode back;
public LinkedListNode()
{
info = 0;
next = null;
back = null;
}
public LinkedListNode(int item)
{
info = item;
next = null;
back = null;
}
public void displayInfo()
{
System.out.print(info + " ");
}
}
protected int count;
protected LinkedListNode first;
protected LinkedListNode last;
public LinkedList()
{
first = null;
last = null;
count = 0;
}
public void initializeList()
{
first = null;
last = null;
count = 0;
}
public boolean isEmpty()
{
return (first == null);
}
public int length()
{
return count;
}
public void print()
{
LinkedListNode current = first;
while (current != null)
{
current.displayInfo();
current = current.next;
}
}
public void insertNode(int insertItem)
{
LinkedListNode newNode = new LinkedListNode(insertItem);
if (isEmpty())
{
first = newNode;
last = newNode;
count++;
}
else
{
last.next = newNode;
newNode.back = last;
}
last = newNode;
}
public LinkedListNode partition(LinkedList list,
LinkedListNode first, LinkedListNode last)
{
LinkedListNode smallIndex = first;
LinkedListNode index = smallIndex.next;
LinkedListNode temp = new LinkedListNode();
int pivot = first.info;
while (index != last.next)
{
if((index.info) < pivot)
{
smallIndex = smallIndex.next;
temp.info = index.info;
index.info = smallIndex.info;
smallIndex.info = temp.info;
}
index = index.next;
}
temp.info = first.info;
first.info = smallIndex.info;
smallIndex.info = temp.info;
System.out.print("The list after QuickSort is: ");
list.print();
System.out.print("\n");
return smallIndex;
}
public void recQuickSort(LinkedList list, LinkedListNode first,
LinkedListNode last)
{
while(first != last)
{
LinkedListNode pivotLocation = partition(list, first, last);
recQuickSort(list, first, pivotLocation.back);
recQuickSort(list, pivotLocation.next, last);
}
}
public void quickSortLinkedList(LinkedList list)
{
recQuickSort(list, list.first, list.last);
}
}
import java.util.*;
public class testLinkedListQuickSort
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
LinkedList linkedlist = new LinkedList();
int num;
System.out.println("Enter numbers to add to linked list:");
num = console.nextInt();
while (num != 0)
{
linkedlist.insertNode(num);
num = console.nextInt();
}
linkedlist.quickSortLinkedList(linkedlist);
linkedlist.print();
}
}
Regarding your comments: you call partition with
recQuickSort(list, first, pivotLocation.back);
Do if pivotLocation.back is null then the partition method is called with last == null which leads to your NPE.
In your partition() method, you're not doing much checking for null values. For instance, if smallIndex, index, temp, or last are null, then that will blow up. There's also first, which if it's null, would cause the NPE.
It's a good idea to ensure that what you're being passed in the recursive call isn't an empty node. I don't see many checks for that.
NullPointerException occurs when you are trying to access a reference where there is no value.
Or when calling the instance method of a null object and accessing or modifying the field of a null object.
Or when you pass null to a method which expects a real value. It means to say that null object is used illegally.
I didnt looked at your code much but to resolve this, determine which Object instance is null and causing the problem. You will need to modify your code in order to add proper null check validations
Related
I am trying to return all node contents that match a given String input. What I am trying to do is essentially a very simple search engine, where the user is able to type in a String and the program returns all characteristically similar contents it can find in the linked list. The linked list itself is built from a file, formatted as
<<Game’s Name 0>>\t<<Game’s Console 0>>\n
<<Game’s Name 1>>\t<<Game’s Console 1>>\n
where the lines are delimited with a \n and the game and its corresponding console are delimited with a \t.
My current methodology follows searching the linked list with a while loop, assigning a temporary value to the head and reassigning it to it's link as it goes down the list. Once the loop finds contents within a node that matches the current input, it stops the loop and returns the data found in the node. I have yet to try if this could be done with a for loop, as the while loop more than likely would not know when to continue once it has found a match. I am also unsure if the while loop argument is the most efficient one to use, as my understanding of it is very minimal. I believe !temp.equals(query) is stating "temp does not equal query," but I have a feeling that this could be done in a more efficient manner.
This is what I have so far, I will provide the entire Generic linked list class for the sake of context, but the method I am questioning is the very last one, found at line 126.
My explicitly stated question is how can I search through a linked list's contents and return those contents through the console.
import java.io.FileNotFoundException;
import java.util.Scanner;
public class GenLL<T>
{
private class ListNode
{
T data;
ListNode link;
public ListNode(T aData, ListNode aLink)
{
data = aData;
link = aLink;
}
}
private ListNode head;
private ListNode current;
private ListNode previous;
private int size;
public GenLL()
{
head = current = previous = null;
this.size = 0;
}
public void add(T aData)
{
ListNode newNode = new ListNode(aData, null);
if (head == null)
{
head = current = newNode;
this.size = 1;
return;
}
ListNode temp = head;
while (temp.link != null)
{
temp = temp.link;
}
temp.link = newNode;
this.size++;
}
public void print()
{
ListNode temp = head;
while (temp != null)
{
System.out.println(temp.data);
temp = temp.link;
}
}
public void addAfterCurrent(T aData)
{
if (current == null)
return;
ListNode newNode = new ListNode(aData, current.link);
current.link = newNode;
this.size++;
}
public T getCurrent()
{
if(current == null)
return null;
return current.data;
}
public void setCurrent(T aData)
{
if(aData == null || current == null)
return;
current.data = aData;
}
public void gotoNext()
{
if(current == null)
return;
previous = current;
current = current.link;
}
public void reset()
{
current = head;
previous = null;
}
public boolean hasMore()
{
return current != null;
}
public void removeCurrent()
{
if (current == head)
{
head = head.link;
current = head;
}
else
{
previous.link = current.link;
current = current.link;
}
if (this.size > 0)
size--;
}
public int getSize()
{
return this.size;
}
public T getAt(int index)
{
if(index < 0 || index >= size)
return null;
ListNode temp = head;
for(int i=0;i<index;i++)
temp = temp.link;
return temp.data;
}
public void setAt(int index, T aData)
{
if(index < 0 || index >= size || aData == null)
return;
ListNode temp = head;
for (int i = 0; i < index; i++)
temp = temp.link;
temp.data = aData;
}
public T search() throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Search: ");
String query = keyboard.nextLine();
ListNode temp = head;
while(!temp.equals(query))
temp = temp.link;
return temp.data;
//plus some sort of print function to display the result in the console
}
}
You can apply regex for every node's content, if the data type is string apply it if it is of some other datatype convert it into string if possible, else throw some exceptions.
I had written my own Linked Class Codes with Node first and last, since there exists a Node last, I encountered problems regarding reference and pointer manipulations when I tried to manually created the LinkedList in the main method and test it.
I am quite familiar with the recursion implemented in the "addFirst" "addLast" and "remove" methods, but now somehow the reference to the Node first becomes null after addFirst Method.
public class LinkedList<T> {
Node first,last,temp;
public class Node{
T value;
Node next;
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
public String toString(){
if(next == null){
return value.toString();
}
else{
return value.toString() + " " + next.toString();
}
}
public T getLL(int index){
if(index == 0){
return value;
}
if(next == null){
throw new
IndexOutOfBoundsException("have reached the end of the list, none found");
}
return next.getLL(index-1);
}
public T removeLL(int x){
if(x == 1){
T value = next.value;
next = next.next;
return value;
}
else if(next == null){
throw new
IndexOutOfBoundsException("have reached the end of the list, none found");
}
else{
return next.removeLL(x-1);
}
}
}
public LinkedList(T value) {
temp = new Node(value,null);
first = new Node(value,null);
last = temp;
}
public static void main(String[] args) {
/**
* [120,110,100,90,80];
*/
LinkedList L = new LinkedList(100);
L.addFirst(110);
L.addFirst(120);
L.addLast(90);
L.addLast(80);
System.out.println(L.size());
System.out.println(L.remove(0));
System.out.println(L.last.toString());
//return null which causes the remove method not to work.
System.out.println(L.first);
}
public void addFirst(T value){
first = new Node(value,first);
}
public void addLast(T value){
Node p = first;
if( p == null){
first = last = new Node(value,null);
}
while(p.next!= null){
p = p.next;
}
last.next = new Node(value,null);
last = new Node(value,null);
}
public T get(int index){
if(first == null){
throw new IndexOutOfBoundsException("empty list");
}
return first.getLL(index);
}
public int size(){
int c = 0;
while(first != null){
first = first.next;
c++;
}
return c;
}
public T remove(int x){
if(first == null){
throw new IndexOutOfBoundsException("Tried to remove from empty list");
}
if (x == 0) {
T value = first.value;
first = first.next;
return value;
}
return first.removeLL(x);
}
}
I expected that the Node first pointed to the first element of the LinkedList instead of pointing to null. Meanwhile, this won't affect the pointer of Node last.
Looks like the problem inside the AddLast function. You braking the list.
Shouldn't it be like this?
public void addLast(T value){
Node p = first;
if( p == null){
first = last = new Node(value,null);
}
while(p.next!= null){
p = p.next;
}
p.next = new Node(value,null);
last = p.next;
//last = new Node(value,null);
}
Update Regarding your comment and updated answer.
Your size function is wrong:
public int size(){
int c = 0;
while(first != null){
first = first.next; // <-- now first point to the last and length is 1
c++;
}
return c;
}
When you remove the first element first is null. You have to create temporary variable to traverse your list. To check this comment the line where you calculate size.
Your are actually not quite right last.next = new Node(value,null); point to the new node. But instead of connecting again last = last.next your new node is gone because you create your new node for the last but last.next pointed to new node and hence last is not last anymore. (I think your understood what I meant)
I insert some elements in Node in java,displaying element also working fine.But when i search any element occurrence using recursive its always return value zero .Sorry wrong for my english.I am new in data structure implementation in java . Thanks
public class pal{
private static Node head;
private static class Node {
private int value;
private Node next;
Node(int value) {
this.value = value;
}
}
public static void addToTheLast(Node node) {
if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.next != null)
temp = temp.next;
temp.next = node;
}
}
public static void printList() {
Node temp = head;
while (temp != null) {
System.out.format("%d ", temp.value);
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
int no ;
Node head = null ;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of Element ");
no = sc.nextInt();
for(int i = 0 ;i< no; i ++){
System.out.print("Enter Element ");
int a = sc.nextInt();
if(head == null){
head = new Node(a);
addToTheLast(head);
}else{
addToTheLast(new Node(a));
}
}
printList();
System.out.print("Enter search key");
int key = sc.nextInt();
int yo = count(head,key);
System.out.print(String.valueOf(yo));
}
public int count (Node head,int key){
int cnt = 0;
if(head == null){
return cnt;
}else{
if(temp.value == key)
cnt++;
count(temp.next,key)
}
return cnt;
}
}
Always retun value 0 if element is present in linklist
Your code does not compile as you are referring to a variable temp within count method, but it does not exist.
You have to replace temp with head.
Also, you are losing the cnt value in your recursive call. You are incrementing cnt which is a local variable.
I have modified the code to pass along the value of count as a parameter.
public static int count(Node head, int key, int count){
if(head == null){
return count;
} else {
if(head.value == key) {
return count(head.next, key, count + 1);
} else {
return count(head.next, key, count);
}
}
}
If you don't want the callers of count to pass 0 to the last parameter (as count(head, key, 0)), make it a private method and make the public search method call this (I prefer this method as it is cleaner)
public static int count(Node head, int key) { //main method calls this
return call(head, key, 0); //calls the above method
}
Having trouble adding nodes to the end of a linked
The code is pretty self explanatory, the addToEnd method adds a single node to the end of a linkedlist.
public class ll5 {
// Private inner class Node
private class Node{
int data;
Node link;
public Node(int x, Node p){
data = x;
link = p;
}
}
// End of Node class
public Node head;
public ll5(){
head = null;
}
public void addToEnd(int data) {
Node p = head;
while (p.link != null)
p=p.link;
p.link=new Node(data, null);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ll5 list = new ll5();
list.printList();
System.out.println("How many values do you want to add to the list");
int toAdd = input.nextInt();
for(int i = 0; i < toAdd; i++) {
System.out.println("Enter value " + (i + 1));
list.addToEnd(input.nextInt());
}
System.out.println("The list is:");
list.printList();
input.close();
}
}
Why is it giving me an NullPointerException error?? The error is somewhere in the while loop in the addToEnd method.
You haven't handled the initial condition when list has nothing and head is null. Because of that you're getting NPE.
Following method should work.
public void addToEnd(int data) {
Node p = head;
if( p == null) {
head = new Node(data, null);
} else {
while (p.link != null)
p=p.link;
p.link=new Node(data, null);
}
}
That's because the head is null at the beginning
public ll5(){
head = null; // <-- head is null
}
public void addToEnd(int data) {
Node p = head; //<-- you assigned head, which is null, to p
while (p.link != null) //<-- p is null, p.link causes NullException
p=p.link;
p.link=new Node(data, null);
}
I've been working through some standard coding interview questions from a book I recently bought, and I came across the following question and answer:
Implement an algorithm to find the nth to last element in a linked list.
Here's the provided answer:
public static LinkedListNode findNtoLast(LinkedListNode head, int n) { //changing LinkedListNode to ListNode<String>
if(head == null || n < 1) {
return null;
}
LinkedListNode p1 = head;
LinkedListNode p2 = head;
for(int j = 0; j < n-1; ++j) {
if(p2 == null) {
return null;
}
p2 = p2.next;
}
if(p2 == null) {
return null;
}
while(p2.next != null) {
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
I understand the algorithm, how it works, and why the book lists this as its answer, but I'm confused about how to access the LinkedListNodes to send as an argument to the method. I know that I'd have to create a LinkedListNode class (since Java doesn't already have one), but I can't seem to figure out how to do that. It's frustrating because I feel like I should know how to do this. Here's something that I've been working on. I'd greatly appreciate any clarification. You can expand/comment on my code or offer your own alternatives. Thanks.
class ListNode<E> {
ListNode<E> next;
E data;
public ListNode(E value) {
data = value;
next = null;
}
public ListNode(E value, ListNode<E> n) {
data = value;
next = n;
}
public void setNext(ListNode<E> n) {
next = n;
}
}
public class MyLinkedList<E> extends LinkedList {
LinkedList<ListNode<E>> list;
ListNode<E> head;
ListNode<E> tail;
ListNode<E> current;
ListNode<E> prev;
public MyLinkedList() {
list = null;
head = null;
tail = null;
current = null;
prev = null;
}
public MyLinkedList(LinkedList<E> paramList) {
list = (LinkedList<ListNode<E>>) paramList; //or maybe create a loop assigning each ListNode a value and next ptr
head = list.getFirst();
tail = list.getLast(); //will need to update tail every time add new node
current = null;
prev = null;
}
public void addNode(E value) {
super.add(value);
//ListNode<E> temp = tail;
current = new ListNode<E>(value);
tail.setNext(current);
tail = current;
}
public LinkedList<ListNode<E>> getList() {
return list;
}
public ListNode<E> getHead() {
return head;
}
public ListNode<E> getTail() {
return tail;
}
public ListNode<E> getCurrent() {
return current;
}
public ListNode<E> getPrev() {
return prev;
}
}
How can the LinkedListNode head from a LinkedList?
Update: I think part of my confusion comes from what to put in the main method. Do I need to create a LinkedList of ListNode? If I do that, how would I connect the ListNodes to each other? How would I connect them without using a LinkedList collection object? If someone could show me how they would code the main method, I think that would put things into enough perspective for me to solve my issues. Here's my latest attempt at the main method:
public static void main(String args[]) {
LinkedList<ListNode<String>> list = new LinkedList<ListNode<String>>();
//MyLinkedList<ListNode<String>> list = new MyLinkedList(linkedList);
list.add(new ListNode<String>("Jeff"));
list.add(new ListNode<String>("Brian"));
list.add(new ListNode<String>("Negin"));
list.add(new ListNode<String>("Alex"));
list.add(new ListNode<String>("Alaina"));
int n = 3;
//ListIterator<String> itr1 = list.listIterator();
//ListIterator<String> itr2 = list.listIterator();
LinkedListNode<String> head = new LinkedListNode(list.getFirst(), null);
//String result = findNtoLast(itr1, itr2, n);
//System.out.println("The " + n + "th to the last value: " + result);
//LinkedListNode<String> nth = findNtoLast(list.getFirst(), n);
ListNode<String> nth = findNtoLast(list.getFirst(), n);
System.out.println("The " + n + "th to the last value: " + nth);
}
In an attempt to connect the nodes without using a custom linked list class, I have edited my ListNode class to the following:
class ListNode<E> {
ListNode<E> next;
ListNode<E> prev; //only used for linking nodes in singly linked list
ListNode<E> current; //also only used for linking nodes in singly linked list
E data;
private static int size = 0;
public ListNode() {
data = null;
next = null;
current = null;
if(size > 0) { //changed from prev != null because no code to make prev not null
prev.setNext(this);
}
size++;
}
public ListNode(E value) {
data = value;
next = null;
current = this;
System.out.println("current is " + current);
if(size > 0) {
prev.setNext(current);//this line causing npe
}
else
{
prev = current;
System.out.println("prev now set to " + prev);
}
size++;
System.out.println("after constructor, size is " + size);
}
public ListNode(E value, ListNode<E> n) {
data = value;
next = n;
current = this;
if(size > 0) {
prev.setNext(this);
}
size++;
}
public void setNext(ListNode<E> n) {
next = n;
}
}
As is right now, the program will run until it reaches prev.setNext(current); in the single argument constructor for ListNode. Neither current nor prev are null at the time this line is reached. Any advice would be greatly appreciated. Thanks.
You don't actually need a separate LinkedList class; the ListNode class is a linked list. Or, to state it differently, a reference to the head of the list is a reference to the list.
The use of head, tail, current, prev in the sample code you posted has come from a double-linked list which is a data type that has links in both directions. This is more efficient for certain types of applications (such as finding the nth last item).
So I would recommend renaming your ListNode class to LinkedList and renaming next to tail.
To add a new item to the list you need a method that creates a new list with the new item at it's head. Here is an example:
class LinkedList<E> {
...
private LinkedList(E value, LinkedList<E> tail) {
this.data = value;
this.tail = tail;
}
public LinkedList<E> prependItem(E item) {
return new LinkedList(item, this);
}
}
Then to add a new item i to list you use list = list.prependItem(i);
If for some reason you need to always add the items to the end, then:
private LinkedList(E value) {
this.data = value;
this.tail = null;
}
public void appendItem(E item) {
LinkedList<E> list = this;
while (list.tail != null)
list = list.tail;
list.tail = new LinkedList<>(item);
}
However this is obviously pretty inefficient for long lists. If you need to do this then either use a different data structure or just reverse the list when you have finished adding to it.
Incidentally, an interesting side effect of this is that a reference to any item in the list is a reference to a linked list. This makes recursion very easy. For example, here's a recursive solution for finding the length of a list:
public int getLength(LinkedList list) {
if (list == null) {
return 0;
} else {
return 1 + getLength(list.getTail());
}
}
And using this a simple (but very inefficient!) solution to the problem you provided - I've renamed the method to make its function more obvious:
public LinkedList getTailOfListOfLengthN(LinkedList list, int n) {
int length = getLength(list);
if (length < n) {
return null;
} else if (length == n) {
return list;
} else {
return getTailOfLengthN(list.getTail(), n);
}
}
And to reverse the list:
public LinkedList<E> reverse() {
if (tail == null) {
return this;
} else {
LinkedList<E> list = reverse(tail);
tail.tail = this;
tail = null;
return list;
}
}
As I hope you can see this makes the methods a lot more elegant than separating the node list classes.
Actually you have created a linked list with you class ListNode.
A linked list is made of a node and a reference to another linked list (see the recursion?).