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;








1















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".










share|improve this question



















  • 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















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".










share|improve this question



















  • 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








1








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".










share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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













  • 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













1 Answer
1






active

oldest

votes


















0














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):



  1. You are trying to implement the Stack class, but in fact you should extend it.

  2. In order to use isEmpty() from the Stack class you need to increment the elementCount++; in the push() method instead of size. As isEmpty() checks elementCount inherited from the Stack class.


  3. The return type of push should not be void instead it should return the argument. (as per the Java doc of the Stack class).



    @Override
    public Object push(Object newElement)
    first = new Node(newElement, first);
    elementCount++;
    return newElement;







share|improve this answer

























  • 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






  • 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











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
);



);













draft saved

draft discarded


















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









0














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):



  1. You are trying to implement the Stack class, but in fact you should extend it.

  2. In order to use isEmpty() from the Stack class you need to increment the elementCount++; in the push() method instead of size. As isEmpty() checks elementCount inherited from the Stack class.


  3. The return type of push should not be void instead it should return the argument. (as per the Java doc of the Stack class).



    @Override
    public Object push(Object newElement)
    first = new Node(newElement, first);
    elementCount++;
    return newElement;







share|improve this answer

























  • 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






  • 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















0














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):



  1. You are trying to implement the Stack class, but in fact you should extend it.

  2. In order to use isEmpty() from the Stack class you need to increment the elementCount++; in the push() method instead of size. As isEmpty() checks elementCount inherited from the Stack class.


  3. The return type of push should not be void instead it should return the argument. (as per the Java doc of the Stack class).



    @Override
    public Object push(Object newElement)
    first = new Node(newElement, first);
    elementCount++;
    return newElement;







share|improve this answer

























  • 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






  • 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













0












0








0







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):



  1. You are trying to implement the Stack class, but in fact you should extend it.

  2. In order to use isEmpty() from the Stack class you need to increment the elementCount++; in the push() method instead of size. As isEmpty() checks elementCount inherited from the Stack class.


  3. The return type of push should not be void instead it should return the argument. (as per the Java doc of the Stack class).



    @Override
    public Object push(Object newElement)
    first = new Node(newElement, first);
    elementCount++;
    return newElement;







share|improve this answer















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):



  1. You are trying to implement the Stack class, but in fact you should extend it.

  2. In order to use isEmpty() from the Stack class you need to increment the elementCount++; in the push() method instead of size. As isEmpty() checks elementCount inherited from the Stack class.


  3. The return type of push should not be void instead it should return the argument. (as per the Java doc of the Stack class).



    @Override
    public Object push(Object newElement)
    first = new Node(newElement, first);
    elementCount++;
    return newElement;








share|improve this answer














share|improve this answer



share|improve this answer








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 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





    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











  • @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





    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



















draft saved

draft discarded
















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현