Get Exception in thread "main" java.lang.NullPointerException with LinkedList - java

Simple Linked List
public class List_manager {
Entry first;
Entry last;
public void add(String el) {
if (isEmpty()) { first=new Entry(el); last=first; return; }
new Entry(el,last);
}
public String get() {
Entry temp=first;
first=first.next;
return temp.data;
}
public boolean isEmpty() {
return first==null;
}
private class Entry {
String data;
Entry next;
public Entry(String data,Entry to) {
this.data=data;
to.next=this;
to=this;
}
public Entry(String data) {
this.data=data;
}
}
}
#The main class#
I added 3 element and list contains only 2... why?
public class Main {
public static void main(String[] args) {
List_manager l=new List_manager();
l.add("1");
l.add("2");
l.add("3");
System.out.println(l.get());
System.out.println(l.get()); // Why here output: "3"??
System.out.println(l.get()); // here is an error occurs
}
}
I really don`t get why list contains 2 elements?
Why it ignores 2nd added element?

to=this; This sentence have no influence on variable 'last', because veriable 'to' is formal parameter, while variable 'last' is actual parameter. So, when you executed this sentence "to = this;" the value of
variable 'last' was not changed to next.That's mean variable 'last' always pointed to the first element.
my change is : new Entry(el,last); --> last = new Entry(el,last);
Things look better.

Think about what your get method is doing. You already noticed some aberrant behavior with it.
public String get() {
Entry temp=first;
first=first.next;
return temp.data;
}
What happens the first time I call this?
temp gets whatever first is pointing to
first is moved to its next element (RED FLAG)
temp's data is returned...
One problem is that you're moving your head reference around - this is a bad idea, since it means that you can never access the true first element in your list ever again.
Now on its own, even with this implementation, you should still be able to get the first element.
The above was just a red herring - although you should not be moving your head pointer around. This is the real problem. What happens on subsequent add calls to your list?
public void add(String el) {
if (isEmpty()) {
first = new Entry(el);
last = first;
return;
}
new Entry(el,last);
}
Only the first element inserted and the last element inserted are respected. All other entries after next are overwritten.
I suggest that you use a debugger to figure this one out, as it stems from a misunderstanding of a good approach to do this. You only want to insert things through your tail pointer once you have one element. Doing this through object creation only causes heartache and confusion.
For posterity, I'll leave you with a sample, verbatim implementation I wrote for a singly linked list implementation I did a while back. It describes a more viable approach to inserting into a list.
public void insert(E data) {
Node<E> candidate = new Node<>(data);
if(head == null) {
head = candidate;
tail = head;
} else {
tail.setNext(candidate);
tail = tail.getNext();
}
size = size + 1;
}

Related

Display letters in reverse order of stacks

I wrote this code of stacks using a linked list but I am having a problem with the code it prints the letters in reverse order without creating a function to display the letters in reverse order
class SimpleLinkedListStack2 implements SimpleStack ,Iterable {
static class ListNode<T> {
public T value;
public ListNode<T> next;
public ListNode(T value, ListNode<T> next) {
this.value = value;
this.next = next;
}
}
private ListNode<T> head = null;
private int count = 0;
public Iterator<T> iterator() {
return new Iterator<T>() {
private ListNode<T> next = head;
#Override
public boolean hasNext() {
return next != null;
}
#Override
public T next() {
if (next == null)
throw new NoSuchElementException();
T value = next.value;
next = next.next;
return value;
}
};
}
#Override
public void push(T value) {
head = new ListNode<>(value, head);
count++;
}
#Override
public T pop() throws Exception {
if (count == 0) {
throw new Exception("Stack is empty");
}
T value = head.value;
head = head.next;
count--;
return value;
}
#Override
public T peek() throws Exception {
if (count == 0) {
throw new Exception("Stack is empty");
}
return head.value;
}
}
this is the main class
public class main {
public static void main(String[] args) {
SimpleLinkedListStack2 <String>stack2= new SimpleLinkedListStack2<>();
stack2.push("a");
stack2.push("b");
stack2.push("c");
stack2.push("d");
stack2.push("e");
for (String letters : stack2){
System.out.println(letters);
}
}
}
the out but is
e
d
c
b
a
because I need to make a function to display the letters in reverse order in the class SimpleLinkedListStack2
Just walk through your code:
stack2.push("a");
This changes your stack's head from null to a node that has no next and whose value is "a". Your stack is now: -> ["a", -> null], where -> is 'pointing at object'.
stack2.push("b");
And now your stack is -> ["b", -> ["a", -> null]]: You create a new ListNode object for "b", and update its 'next' pointer to be what head was, and then head points at this newly created thing.
Thus, of course, if you then iterate through it, you get the last thing you added ("b" here), first.
Hence, your code pritns e d c b a - it's what you put in the list, in reverse order, because that's what you programmed, and that's what stacks are (they are 'Last in, First Out' - the last thing you put it is the e, and that's the first thing that comes out, as per the design!
But I want to print in the same order I put the items in!
This is a so-called 'singly linked list', meaning, any given LinkedNode knows its next node, but does not know its previous node. You cannot in-place reverse-walk-through a singly linked list - what you want is not possible without drastic steps.
For example, you could make an entirely new stack, just by iterating through this stack, which naturally ends up with the newly created stack being the exact reverse of the original. And then print that reversed stack, and then toss it away (java is garbage collected; that part happens automatically). There is no 'easy' solution / no solution that takes no memory. You could also just build the string out, and then reverse that instead.
Perhaps that's the point of this homework exercise, to make you think about how these LinkedNode objects relate to each other in memory. Get out a pad of paper and go sketch it out. Boxes and arrows. You'll figure it out.

Question about Conceptual Understanding for Circular doubly linked list in Java

I am a beginner coder in java and in general and I wanted to ask for some help. I am doing an assignment in which I am supposed to make a CircularLinkedList which is like a DoublyLinkedList. But for CircularLinkedList am not allowed to have a head or a tail. Instead, I have a pointer to one of the nodes in the CircularLinkedList. So, to my understanding from basic LinkedList, the head node is where we would implement our series of Singly LinkedList.
I have made a DoubleNode pointer as a global variable that will at first point at the first node when we create a circular linked list. when I construct a CircularLinkedList that is empty.
My question is: Should this DoubleNode pointer point to null within the constructor or should I just create a new node and make them point to null with not value to claim its empty?
I am posting my code for better understanding my concept
public class CircularLinkedList<T> {
DoubleNode pointer; //create a double node of pointer [/| no data |\]
int lengthoflinkedlist = 0;
private class DoubleNode<T> { //create a DoubleNode class to understand how nodes would look in the circular linked list
private DoubleNode prev;
private T data;
private DoubleNode next;
// Now we input our functions into the class or methods as they call it
public DoubleNode(){ //constructors for bas node.
this.prev = null;
this.next = null;
}
public DoubleNode(T data) {
this.prev = null;
this.data = data;
this.next = null;
}
public DoubleNode(DoubleNode P, T data, DoubleNode N){
this.prev = P;
this.data = data;
this.next = N;
}
}
public CircularLinkedList() {
// pointer
DoubleNode A = new DoubleNode(); // creates a node with nothing and pointers to null;
}
public CircularLinkedList(int initSize, T initValue) { //constucting a circular linked list
// TODO implement me
//initSize means the size of linkedlist
//initValue means the value of data T in the nodes.
if(initSize == 0) { //throw error as length 0 means linkedlist is empty
System.out.println("The linked list with size 0 means it is an empty linkedlist with a Pointer pointing to Nothing");
}
else {
DoubleNode check = this.pointer;
for(int lengthoflinkedlist = 0; lengthoflinkedlist < initSize - 1; lengthoflinkedlist++) {
DoubleNode A = new DoubleNode(this.pointer.next,initValue,this.pointer.prev);
}
}
}
public void moveForward() {
// TODO implement me
}
public void moveBackward() {
// TODO implement me
}
public T getValue() {
// TODO implement me
return null;
}
/**
* #return the previous value of the updated node
*/
public T setValue(T value) {
// TODO implement me
return null;
}
public void addBefore(T value) {
// TODO implement me
}
public void addAfter(T value) {
// TODO implement me
}
/**
* #return the previous value of the removed node
*/
public T removeBefore() {
// TODO implement me
return null;
}
/**
* #return the previous value of the removed node
*/
public T removeAfter() {
// TODO implement me
return null;
}
public boolean isEmpty() {
// TODO implement me
return true;
}
}
I am still implementing my class and constructors atm so i need help based on that
My question is, first of, I have made a DoubleNode pointer as a global variable that will at first point at the first node when we create a circular linked list.
I can't see a "global" variable. I can see an instance variable called pointer ... which I assume is what you are talking about.
Should this DoubleNode pointer point to null within the constructor or should I just create a new node and make them point to null with not value to claim its empty?
Actually, you can do it either way.
One way would be to have an empty list represented as a CircularLinkedList with a null value in the pointer field.
Another way would be to have an empty list represented as a CircularLinkedList with a pointer that refers to a DoubleNode with null data.
I think that the first approach will be simpler. Either way you need special case code for when the list is empty.
You wrote:
But for CircularLinkedList am not allowed to have a head or a tail.
I would expect this to be true since a circle doesn't have a concrete beginning or end. In a circle, they are arbitrary. Unlike a conventional list, when a circular list is empty, the head (beginning node) is whatever you want it to be. The trick is how you calculate the end. This is important because at some point you need to calculate if the circular list is full.
Assume this array is your "circular list". You could literally decide to make your first insertion right in the middle (index 2). In this case, the "tail" will be your starting index minus 1 (i.e. 1). The problem is, how do you wrap around when you reach index 4 to go to index 0 for the next insertion?
To increment an index in a wrap around manner, you need to use the following formula: index = (index + 1) % N where N is the size of the list; in this case 5.
Now, how do you know your circular list is full? This is actually pretty simple. Before you insert, you will "peek" to the next location to see if there is something there already. If the next slot in your circular list is empty, you can then insert. ON the other hand, if the next slot is full, your list is full.
Last, you need to consider going in reverse order (i.e. to get previous node). The technique is the same. First, you will "peek" the previous index to see if there something there. If the previous slot has a node, you can freely do what you need with it.
The rest of things to considered are unknown to me because your post is not very specific.

Constructor Node cannot be applied to given types while working with nodes

I am working on a code that puts new elements on MyStack if they are unique. I had to copy and paste the node starting code, so I'm having a bit of trouble with an issue. I keep getting two error messages, even after trying various workarounds and I'm not really understanding why. I've even tried using some helper functions I've previously made that have worked before so I'm extra confused.
The two errors I consistently get are:
-cannot infer type arguments for MyStack.Node (actual and formal arguments differ in length)
-constructor node cannot be applied to given types. Required, no arguments, found: anything,
Here's my code:
public class MyStack<Anything>
{
private Node first, last;
private class Node<Anything>
{
Anything item;
Node next;
}
public boolean contains(Anything value)
{
for (Node curr = first; curr != null; curr = curr.next)
{
if (value.equals(curr.item)) {
return true;
}
}
return false;
}
public void add(Anything value)
//method that adds a new value to the end of the list
//COMPLETE
{
Node temp = first;
while(temp.next!=null){ //finds the end
temp=temp.next;
}
temp.next=new Node(value, null); //assigns new value
}
public void enqueue(Anything info){
if (this.contains(info)==true) { //if the info is already present
System.out.println("the stack already contains this value");
return;
}
//if we actually need to add the info
if (first == null) { //if there is nothing in the stack
Node temp= first;
first = new Node<>(info,temp);
first = temp;
return;
}
if (first != null) { //if there is already stuff
Node temp = first;
while (temp.next == null)
{ Node newNode= new Node<>(info, temp);
temp.next = newNode;
}
return;
}
}
}
As #Andreas already pointed out, Node needs a constructor.
There are a few other flaws in your Code:
Use Generics
With your Code, you can only store Objects of the class Anything, what strongly limits its reusability. Use a generic instead and you can reuse this class for many more purposes.
Linked List
I suggest, you use the paradigm of a double-linked-list. That way you do not need to find the last Node to add something to the Stack. Node now has a pointer to its previous and next element.
Use the last Object
You have the object last but never use it. To find out, whether the current object is the last one you compare the value to null. This has the effect, that storing a null value will break your List. Instead compare to the Object last, this object is unique and guarantees you, that you are at the end of the list. Both first and last are Nodes that do not contain a value and are simply used to mark the start/end of your List.
Adding elements
Using the changes above, the code in the Method enqueue(T value) becomes significantly simpler: You just check whether contains(value) and decide whether you add the value to the List or not.
All these changes applied result in following code:
public class MyStack<T extends Object> {
private Node first, last;
public MyStack() {
first = new Node(null, null, null);
last = new Node(null, null, first);
first.next = last;
}
private class Node {
T item;
Node next;
Node previous;
public Node(T item, Node next, Node previous) {
this.item = item;
this.next = next;
this.previous = previous;
}
}
public boolean contains(T value) {
for (Node curr = first.next; curr != last; curr = curr.next) {
if (value.equals(curr.item)) {
return true;
}
}
return false;
}
/**
* method that adds a new value to the end of the list
*/
public void add(T value)
{
Node secondLast = last.previous;
Node added = new Node(value, last, secondLast);
secondLast.next = added;
last.previous = added;
}
/**
* only adds value if it is not already contained by the Stack
*/
public void enqueue(T value) {
if (this.contains(value) == true) { // if the info is already present
System.out.println("the stack already contains this value");
}
else {
add(value);
}
}
public static void main(String[] args) {
MyStack<String> test = new MyStack<>();
test.add("foo");
test.add("bar");
test.add("baz");
System.out.println(test.contains("bar"));
System.out.println(test.contains("new"));
test.enqueue("baz");
test.enqueue("MyStack");
}
}
Naming
As you may have noticed, in my explanation I called this class a List. This is because it fulfills more of the characteristics of a List. A Stack usually only provides the methods push to put something at the top of the Stack and pop to remove and return the topmost Object. Optionally peek can return the topmost Object, without removing it from the Stack.
Also consider renaming the method enqueue: enqueue is used in Queues (obviously) and Queues do not forbid to add two equal Objects. So the name is misleading. I would call this method something like addIfNotContaining.
In my Opinion you should name this class to be a List and add a method get(int i) to get a specific element at a position. Naturally adding some other methods like size ect. to comply with a standard List. But I assume you already had, but did not post them because they are not related to your problem.
Multithreading
This Class is far from threadsave. But I let you figure out yourself how to make it threadsave if needed.

How to find the first value in a linked list?

I have a linked list I'm given and I need to find the first value in the list via a getFirst method.I need to display an error message and quit the program if the value is null. The linked list is already given to me link so:
class MyLinkedList
{
private class Node // inner class
{
private Node link;
private int x;
}
//----------------------------------
private Node first = null; // initial value is null
//----------------------------------
public void addFirst(int d)
{
Node newNode = new Node(); // create new node
newNode.x = d; // init data field in new node
newNode.link = first; // new node points to first node
first = newNode; // first now points to new node
}
//----------------------------------
public void traverse()
{
Node p = first;
while (p != null) // do loop until p goes null
{
System.out.println(p.x); // display data
p = p.link; // move p to next node
}
}
}
//==============================================
class TestMyLinkedList
{
public static void main(String[] args)
{
MyLinkedList list = new MyLinkedList();
list.addFirst(1);
list.addFirst(2);
list.addFirst(3);
System.out.println("Numbers on list");
list.traverse();
}
}
Here's what I tried out for the method:
public static Node getFirst(Node list)
{
if (list == null)
{
System.out.println("Error!");
System.exit(1);
}
return MyLinkedList.first;
}
I know this isn't exactly right, we just started this in my class so I'm having trouble understanding what's going on with it. Thank you!
I think you should look at https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html and get an idea for the behavior of a linked list initially. Once you have an idea on how it behaves, you can think about how to add functionality around it. Right now you just have a single method which you call more than you should. What also might help is to create an interface and document it so you know what each method should do.
You should check that first isn't null in order to do what you describe in the question. Also, it is kind of weird that the first node autoreferences itself because usually it is left in null until you add another node
notice that the first value is linked to the first Node with is null. Then you have to check two things
Node == null (you got this)
Node.next == null (you have to do this)
When Node.next == null. It means that Node is first value because it is linked to the initial Node with is null.
Then you have
public static Node getFirst(Node list)
{
// if the list is empty
if (list == null)
{
System.out.println("Error!");
System.exit(1);
} else if(list.link == null) {
// this is the first value!
return list;
} else {
// keep searching recursive with the next Node
return getFirst(list.link);
}
}
The class MyLinkedList in your question follows the pattern of a stack data structure(At the time when i am writing this answer). That is: ever time you add a new element, the new element replaces the previously added element as the first element.
I guess you want to get 1 as your first element, if you have added elements 1,2,3 in that order. Correct me if i am wrong.
In that case your linked list and it's retrieval should be like this:
(Note: i have avoided private vars , public getter , settter , etc; to make code easily readable. But readers should add them.)
class Node{ int x; Node next; }
class LinkedList
{ Node head,tail;
void add(int y)
{ Node node = new Node();
node.x=y;
if(head==null)
head = tail = node;
else
tail = tail.next = node;
}
int getFirst()
{ if(head!=null)
return head.x;
else
throw new java.util.NoSuchElementException("List is empty");
}
}
If you look at java.util.LinkedList, you will find methods that are conventionally used in linked lists. If this is not a homework question, then i suggest you do not reinvent the wheel. Just use the existing libraries.
If you have to use the stack data structure, and you cannot change it, then i suggest you have to change your getFirst() like this:
int getFirst()
{ if(tail!=null)
return tail.x;
else
throw new java.util.NoSuchElementException("List is empty");
}
If you not allowed to add Node tail in your code, then your getFirst() will look like this:
int getFirst()
{ if(head==null)
throw new java.util.NoSuchElementException("List is empty");
Node node = head;
while(node.next!=null)
node=node.next;
return node.x;
}

Doubly Linked List - InsertAfter - Java

First of all, let me say that this is an assignment for a class where we have been tasked with writing our own doubly linked list class and cannot use anything from Java SE (e.g. the LinkedList class). We have to make our code work with a provided driver class. I am not asking for anyone to do the homework for me, I am simply asking for some kind of clarification as to how exactly to implement these methods, since I have struggled with this on and off over the past few days.
We have been provided with an Interface, textEditor.java that provides methods which will be utilized by the driver class, driver.java. These methods include the typical insert, et. al. but my concern is the insertAfter(int lineNum, E line) method and its counterpart, insertBefore. I have not been able to get these to work because comparing int to E, despite my best efforts and reading through several Java texts for guidance.
Below is the code in the DoublyLinkedList.java file, as provided at onset. I would like to know how I can implement some kind of indexing and checking in order to be able to make an insertion following or preceding the line entered by the user/driver class.
public class DoublyLinkedList<E> implements TextEditor<E>
{
Node<E> head, tail;
public DoublyLinkedList()
{
head = null;
tail = null;
}
public boolean isEmpty()
{
return (head == null);
}
public void insert(E line)
{
}
public void insertAfter(int lineNum, E line)
{
}
public void insertBefore(int lineNum, E line) throws IndexOutOfBoundsException
{
}
public void deleteByPosition(int position)
{
}
public void printNode(int position)
{
}
public void printAllNodes()
{
}
}
I have not been able to do this, and having tried several things over several hours, I have given up hope of being able to do it. If I don't find help here or still can't get these methods to work, I will be speaking with my instructor. It may simply be that I am overthinking the problem, and I hope that that is the case.
I'm assuming that your Node class looks like this :
class Node<E> {
private Node next;
private E value;
[...]
}
You can add an attribute in your DoublyLinkedList class, in which you keep the number of Node that your list contains.
Then, if you want the Nth element of your list, you can do this :
private Node getNthElement(int n) {
Node node = head;
for (int i=0; i<n; i++) {
node = node.next;
}
return node;
}
These methods should also check if there are enough elements in the list, etc. But this is the main idea.

Categories

Resources