first node data in LinkedList not being recognized when calledWhen to use LinkedList over ArrayList in Java?Duplicate a LinkedList with a pointer to a random node apart from the next nodeOGNL setValue target is nullStack Simulation with Double Linked ListClone a Singleton objectMethod override returns nullOverriding private methods in (non-)static classesPrinting an array with no elements?Hibernate : Why FetchType.LAZY-annotated collection property eagerly loading?How to change stack push() the second result's next is [object]?
How long can fsck take on a 30 TB volume?
Why does this pattern in powers happen?
How can it be that ssh somename works, while nslookup somename does not?
As a small race with a heavy weapon, does enlage remove the disadvantage?
Would the rotation of the starfield from a ring station be too disorienting?
Trying to understand a summation
Is there an application which does HTTP PUT?
Mindfulness of Watching Youtube
Are wands in any sort of book going to be too much like Harry Potter?
Align a table column at a specific symbol
Where do 5 or more U.S. counties meet in a single point?
History: Per Leviticus 19:27 would the apostles have had corner locks ala Hassidim today?
How to append code verbatim to .bashrc?
Is it safe to keep the GPU on 100% utilization for a very long time?
My Sixteen Friendly Students
What is the Ancient One's mistake?
Can the president of the United States be guilty of insider trading?
Why did Missandei say this?
Should one save up to purchase a house/condo or maximize their 401(k) first?
Is the tensor product (of vector spaces) commutative?
Is it possible to do moon sighting in advance for 5 years with 100% accuracy?
Company stopped paying my salary. What are my options?
While drilling into kitchen wall, hit a wire - any advice?
Was Mohammed the most popular first name for boys born in Berlin in 2018?
first node data in LinkedList not being recognized when called
When to use LinkedList over ArrayList in Java?Duplicate a LinkedList with a pointer to a random node apart from the next nodeOGNL setValue target is nullStack Simulation with Double Linked ListClone a Singleton objectMethod override returns nullOverriding private methods in (non-)static classesPrinting an array with no elements?Hibernate : Why FetchType.LAZY-annotated collection property eagerly loading?How to change stack push() the second result's next is [object]?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I created a stack data structure from scratch using a linked list. It seems to push()
properly because I can use the display method using first.data
, and it displays the list. But when I use peek()
I get a NoSuchElementException
because there is an if statement if (first == null)
, but first should not be null
.
I am not sure how to tackle this differently.
public class StackNew implements Stack{ //Stack is an interface given by my professor
private int size;
private class Node
public Object data;
public Node next;
public Node(Object data, Node next)
this.data = data;
this.next = next;
private Node first = null;
public void push(Object newElement)
first = new Node(newElement, first);
size++;
public Object peek()
if (first == null)
throw new NoSuchElementException();
return first.data;
public void display()
Node previous = null;
while(first != null)
System.out.println((first.data));
previous = first;
first = first.next;
public static void main(String args[])
StackNew stack = new StackNew();
stack.push("java");
stack.push(1);
stack.push("code");
stack.display();
System.out.println(stack.isEmpty());
stack.peek();
When I try to use the peek() method, the first node is null, when it should contain "code".
java stack
add a comment |
I created a stack data structure from scratch using a linked list. It seems to push()
properly because I can use the display method using first.data
, and it displays the list. But when I use peek()
I get a NoSuchElementException
because there is an if statement if (first == null)
, but first should not be null
.
I am not sure how to tackle this differently.
public class StackNew implements Stack{ //Stack is an interface given by my professor
private int size;
private class Node
public Object data;
public Node next;
public Node(Object data, Node next)
this.data = data;
this.next = next;
private Node first = null;
public void push(Object newElement)
first = new Node(newElement, first);
size++;
public Object peek()
if (first == null)
throw new NoSuchElementException();
return first.data;
public void display()
Node previous = null;
while(first != null)
System.out.println((first.data));
previous = first;
first = first.next;
public static void main(String args[])
StackNew stack = new StackNew();
stack.push("java");
stack.push(1);
stack.push("code");
stack.display();
System.out.println(stack.isEmpty());
stack.peek();
When I try to use the peek() method, the first node is null, when it should contain "code".
java stack
1
I recommend you clean up your code a bit. As of now it's not even compiling because you're trying to implement a class (Stack) instead of an Interface. It also has unused variables and the method push returns the wrong type. I don't even see how you managed to compile and run this in its current state. That said, Amardeep's answer is probably correct for the code that you actually tried to run.
– Sebastiaan van den Broek
Mar 23 at 7:24
add a comment |
I created a stack data structure from scratch using a linked list. It seems to push()
properly because I can use the display method using first.data
, and it displays the list. But when I use peek()
I get a NoSuchElementException
because there is an if statement if (first == null)
, but first should not be null
.
I am not sure how to tackle this differently.
public class StackNew implements Stack{ //Stack is an interface given by my professor
private int size;
private class Node
public Object data;
public Node next;
public Node(Object data, Node next)
this.data = data;
this.next = next;
private Node first = null;
public void push(Object newElement)
first = new Node(newElement, first);
size++;
public Object peek()
if (first == null)
throw new NoSuchElementException();
return first.data;
public void display()
Node previous = null;
while(first != null)
System.out.println((first.data));
previous = first;
first = first.next;
public static void main(String args[])
StackNew stack = new StackNew();
stack.push("java");
stack.push(1);
stack.push("code");
stack.display();
System.out.println(stack.isEmpty());
stack.peek();
When I try to use the peek() method, the first node is null, when it should contain "code".
java stack
I created a stack data structure from scratch using a linked list. It seems to push()
properly because I can use the display method using first.data
, and it displays the list. But when I use peek()
I get a NoSuchElementException
because there is an if statement if (first == null)
, but first should not be null
.
I am not sure how to tackle this differently.
public class StackNew implements Stack{ //Stack is an interface given by my professor
private int size;
private class Node
public Object data;
public Node next;
public Node(Object data, Node next)
this.data = data;
this.next = next;
private Node first = null;
public void push(Object newElement)
first = new Node(newElement, first);
size++;
public Object peek()
if (first == null)
throw new NoSuchElementException();
return first.data;
public void display()
Node previous = null;
while(first != null)
System.out.println((first.data));
previous = first;
first = first.next;
public static void main(String args[])
StackNew stack = new StackNew();
stack.push("java");
stack.push(1);
stack.push("code");
stack.display();
System.out.println(stack.isEmpty());
stack.peek();
When I try to use the peek() method, the first node is null, when it should contain "code".
java stack
java stack
edited Mar 23 at 14:27
Josh Pehling
asked Mar 23 at 7:16
Josh PehlingJosh Pehling
134
134
1
I recommend you clean up your code a bit. As of now it's not even compiling because you're trying to implement a class (Stack) instead of an Interface. It also has unused variables and the method push returns the wrong type. I don't even see how you managed to compile and run this in its current state. That said, Amardeep's answer is probably correct for the code that you actually tried to run.
– Sebastiaan van den Broek
Mar 23 at 7:24
add a comment |
1
I recommend you clean up your code a bit. As of now it's not even compiling because you're trying to implement a class (Stack) instead of an Interface. It also has unused variables and the method push returns the wrong type. I don't even see how you managed to compile and run this in its current state. That said, Amardeep's answer is probably correct for the code that you actually tried to run.
– Sebastiaan van den Broek
Mar 23 at 7:24
1
1
I recommend you clean up your code a bit. As of now it's not even compiling because you're trying to implement a class (Stack) instead of an Interface. It also has unused variables and the method push returns the wrong type. I don't even see how you managed to compile and run this in its current state. That said, Amardeep's answer is probably correct for the code that you actually tried to run.
– Sebastiaan van den Broek
Mar 23 at 7:24
I recommend you clean up your code a bit. As of now it's not even compiling because you're trying to implement a class (Stack) instead of an Interface. It also has unused variables and the method push returns the wrong type. I don't even see how you managed to compile and run this in its current state. That said, Amardeep's answer is probably correct for the code that you actually tried to run.
– Sebastiaan van den Broek
Mar 23 at 7:24
add a comment |
1 Answer
1
active
oldest
votes
In your code you would notice that you are getting the error only when you call display
method.
This is because in your implementation, you are overwriting the first
to first.next
which ultimately becomes null in the last iteration of the while
loop. So you need a new pointer that will keep track of the current element and that will progress to the next element without impacting the first
pointer.
So you need to correct the display
method to:
public void display()
Node current = first;
while(current != null)
System.out.println((current.data));
current = current.next;
Here a new pointer current
will keep track of the current element and in the while loop will consecutively print the elements.
Some other issues in your code (if you are trying to extend java.util.Stack
):
- You are trying to
implement
theStack
class, but in fact you shouldextend
it. - In order to use
isEmpty()
from theStack
class you need to increment theelementCount++;
in thepush()
method instead ofsize
. AsisEmpty()
checkselementCount
inherited from theStack
class. The return type of
push
should not bevoid
instead it should return the argument. (as per the Java doc of theStack
class).@Override
public Object push(Object newElement)
first = new Node(newElement, first);
elementCount++;
return newElement;
Thank you for the response, but part of the assignment is to use an interface, and the push method given is void, but I was asking for my peek() and pop() methods are getting errors on first.data lines.
– Josh Pehling
Mar 23 at 14:16
@JoshPehling your peek method was throwingNoSuchElementException
right? that was because you were setting the first pointer tonull
in thedisplay
method. If you fix thedisplay
method and then callpeek
you would not get that exception anymore.
– Amardeep Bhowmick
Mar 23 at 14:19
1
Ahhh I see, because the node previous was null, and I set first to previous. Thank you very much.
– Josh Pehling
Mar 23 at 14:24
@JoshPehling Glad I could help out!
– Amardeep Bhowmick
Mar 23 at 14:25
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55311525%2ffirst-node-data-in-linkedlist-not-being-recognized-when-called%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
In your code you would notice that you are getting the error only when you call display
method.
This is because in your implementation, you are overwriting the first
to first.next
which ultimately becomes null in the last iteration of the while
loop. So you need a new pointer that will keep track of the current element and that will progress to the next element without impacting the first
pointer.
So you need to correct the display
method to:
public void display()
Node current = first;
while(current != null)
System.out.println((current.data));
current = current.next;
Here a new pointer current
will keep track of the current element and in the while loop will consecutively print the elements.
Some other issues in your code (if you are trying to extend java.util.Stack
):
- You are trying to
implement
theStack
class, but in fact you shouldextend
it. - In order to use
isEmpty()
from theStack
class you need to increment theelementCount++;
in thepush()
method instead ofsize
. AsisEmpty()
checkselementCount
inherited from theStack
class. The return type of
push
should not bevoid
instead it should return the argument. (as per the Java doc of theStack
class).@Override
public Object push(Object newElement)
first = new Node(newElement, first);
elementCount++;
return newElement;
Thank you for the response, but part of the assignment is to use an interface, and the push method given is void, but I was asking for my peek() and pop() methods are getting errors on first.data lines.
– Josh Pehling
Mar 23 at 14:16
@JoshPehling your peek method was throwingNoSuchElementException
right? that was because you were setting the first pointer tonull
in thedisplay
method. If you fix thedisplay
method and then callpeek
you would not get that exception anymore.
– Amardeep Bhowmick
Mar 23 at 14:19
1
Ahhh I see, because the node previous was null, and I set first to previous. Thank you very much.
– Josh Pehling
Mar 23 at 14:24
@JoshPehling Glad I could help out!
– Amardeep Bhowmick
Mar 23 at 14:25
add a comment |
In your code you would notice that you are getting the error only when you call display
method.
This is because in your implementation, you are overwriting the first
to first.next
which ultimately becomes null in the last iteration of the while
loop. So you need a new pointer that will keep track of the current element and that will progress to the next element without impacting the first
pointer.
So you need to correct the display
method to:
public void display()
Node current = first;
while(current != null)
System.out.println((current.data));
current = current.next;
Here a new pointer current
will keep track of the current element and in the while loop will consecutively print the elements.
Some other issues in your code (if you are trying to extend java.util.Stack
):
- You are trying to
implement
theStack
class, but in fact you shouldextend
it. - In order to use
isEmpty()
from theStack
class you need to increment theelementCount++;
in thepush()
method instead ofsize
. AsisEmpty()
checkselementCount
inherited from theStack
class. The return type of
push
should not bevoid
instead it should return the argument. (as per the Java doc of theStack
class).@Override
public Object push(Object newElement)
first = new Node(newElement, first);
elementCount++;
return newElement;
Thank you for the response, but part of the assignment is to use an interface, and the push method given is void, but I was asking for my peek() and pop() methods are getting errors on first.data lines.
– Josh Pehling
Mar 23 at 14:16
@JoshPehling your peek method was throwingNoSuchElementException
right? that was because you were setting the first pointer tonull
in thedisplay
method. If you fix thedisplay
method and then callpeek
you would not get that exception anymore.
– Amardeep Bhowmick
Mar 23 at 14:19
1
Ahhh I see, because the node previous was null, and I set first to previous. Thank you very much.
– Josh Pehling
Mar 23 at 14:24
@JoshPehling Glad I could help out!
– Amardeep Bhowmick
Mar 23 at 14:25
add a comment |
In your code you would notice that you are getting the error only when you call display
method.
This is because in your implementation, you are overwriting the first
to first.next
which ultimately becomes null in the last iteration of the while
loop. So you need a new pointer that will keep track of the current element and that will progress to the next element without impacting the first
pointer.
So you need to correct the display
method to:
public void display()
Node current = first;
while(current != null)
System.out.println((current.data));
current = current.next;
Here a new pointer current
will keep track of the current element and in the while loop will consecutively print the elements.
Some other issues in your code (if you are trying to extend java.util.Stack
):
- You are trying to
implement
theStack
class, but in fact you shouldextend
it. - In order to use
isEmpty()
from theStack
class you need to increment theelementCount++;
in thepush()
method instead ofsize
. AsisEmpty()
checkselementCount
inherited from theStack
class. The return type of
push
should not bevoid
instead it should return the argument. (as per the Java doc of theStack
class).@Override
public Object push(Object newElement)
first = new Node(newElement, first);
elementCount++;
return newElement;
In your code you would notice that you are getting the error only when you call display
method.
This is because in your implementation, you are overwriting the first
to first.next
which ultimately becomes null in the last iteration of the while
loop. So you need a new pointer that will keep track of the current element and that will progress to the next element without impacting the first
pointer.
So you need to correct the display
method to:
public void display()
Node current = first;
while(current != null)
System.out.println((current.data));
current = current.next;
Here a new pointer current
will keep track of the current element and in the while loop will consecutively print the elements.
Some other issues in your code (if you are trying to extend java.util.Stack
):
- You are trying to
implement
theStack
class, but in fact you shouldextend
it. - In order to use
isEmpty()
from theStack
class you need to increment theelementCount++;
in thepush()
method instead ofsize
. AsisEmpty()
checkselementCount
inherited from theStack
class. The return type of
push
should not bevoid
instead it should return the argument. (as per the Java doc of theStack
class).@Override
public Object push(Object newElement)
first = new Node(newElement, first);
elementCount++;
return newElement;
edited Mar 23 at 14:23
answered Mar 23 at 7:25
Amardeep BhowmickAmardeep Bhowmick
6,51621231
6,51621231
Thank you for the response, but part of the assignment is to use an interface, and the push method given is void, but I was asking for my peek() and pop() methods are getting errors on first.data lines.
– Josh Pehling
Mar 23 at 14:16
@JoshPehling your peek method was throwingNoSuchElementException
right? that was because you were setting the first pointer tonull
in thedisplay
method. If you fix thedisplay
method and then callpeek
you would not get that exception anymore.
– Amardeep Bhowmick
Mar 23 at 14:19
1
Ahhh I see, because the node previous was null, and I set first to previous. Thank you very much.
– Josh Pehling
Mar 23 at 14:24
@JoshPehling Glad I could help out!
– Amardeep Bhowmick
Mar 23 at 14:25
add a comment |
Thank you for the response, but part of the assignment is to use an interface, and the push method given is void, but I was asking for my peek() and pop() methods are getting errors on first.data lines.
– Josh Pehling
Mar 23 at 14:16
@JoshPehling your peek method was throwingNoSuchElementException
right? that was because you were setting the first pointer tonull
in thedisplay
method. If you fix thedisplay
method and then callpeek
you would not get that exception anymore.
– Amardeep Bhowmick
Mar 23 at 14:19
1
Ahhh I see, because the node previous was null, and I set first to previous. Thank you very much.
– Josh Pehling
Mar 23 at 14:24
@JoshPehling Glad I could help out!
– Amardeep Bhowmick
Mar 23 at 14:25
Thank you for the response, but part of the assignment is to use an interface, and the push method given is void, but I was asking for my peek() and pop() methods are getting errors on first.data lines.
– Josh Pehling
Mar 23 at 14:16
Thank you for the response, but part of the assignment is to use an interface, and the push method given is void, but I was asking for my peek() and pop() methods are getting errors on first.data lines.
– Josh Pehling
Mar 23 at 14:16
@JoshPehling your peek method was throwing
NoSuchElementException
right? that was because you were setting the first pointer to null
in the display
method. If you fix the display
method and then call peek
you would not get that exception anymore.– Amardeep Bhowmick
Mar 23 at 14:19
@JoshPehling your peek method was throwing
NoSuchElementException
right? that was because you were setting the first pointer to null
in the display
method. If you fix the display
method and then call peek
you would not get that exception anymore.– Amardeep Bhowmick
Mar 23 at 14:19
1
1
Ahhh I see, because the node previous was null, and I set first to previous. Thank you very much.
– Josh Pehling
Mar 23 at 14:24
Ahhh I see, because the node previous was null, and I set first to previous. Thank you very much.
– Josh Pehling
Mar 23 at 14:24
@JoshPehling Glad I could help out!
– Amardeep Bhowmick
Mar 23 at 14:25
@JoshPehling Glad I could help out!
– Amardeep Bhowmick
Mar 23 at 14:25
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55311525%2ffirst-node-data-in-linkedlist-not-being-recognized-when-called%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
I recommend you clean up your code a bit. As of now it's not even compiling because you're trying to implement a class (Stack) instead of an Interface. It also has unused variables and the method push returns the wrong type. I don't even see how you managed to compile and run this in its current state. That said, Amardeep's answer is probably correct for the code that you actually tried to run.
– Sebastiaan van den Broek
Mar 23 at 7:24