So I´m trying to code the basics of a stack data structure and when I run the class in sample_stack it´s simply not running and not printing the words and instead just printing "null" :( does anyone know why? apologies if this is obvious
STACK JAVA CLASS:
import java.util.NoSuchElementException;
public class Stack {
// private inner class node
private class Node{
private String item;
private Node link;
public Node() {
item = null;
link = null;
}
public Node(String item, Node link) {
item = this.item;
link = this.link;
}
} // end of inner class
private Node head;
public Stack() {
head = null;
}
// method: PUSH into stack (like addToStart)
public void push(String itemName) {
head = new Node(itemName, head); // so head is the top of the stack ????
}
// method: POP out of stack
public String pop() {
if (head == null) throw new IllegalStateException();
else {
String returnItem = head.item;
head = head.link; // the second top item becomes the new head
return returnItem;
}
}
// method: is it empty?
public boolean isEmpty() {
return ( head == null );
}
}
CLASS USING THE STACK JAVA CLASS:
public class Stack_Example {
public static void main (String[] args) {
Stack message = new Stack();
message.push("Hi");
System.out.println(message.pop());
message.push("my");
message.push("name");
message.push("is");
message.push("JARVIS");
while (!message.isEmpty()) { // while true
String s = message.pop();
System.out.println(s);
}
}
}
Thank you in advance!
public void push(String itemName) {
head = new Node(itemName, head); // so head is the top of the stack ????
}
head is null when you call the constructor, and so the link here, public Node(String item, Node link) { is always null
Don't you want,
public void push(String itemName) {
head = new Node(itemName, this);
}
instead?
Also, this is backwards:
public Node(String item, Node link) {
item = this.item;
link = this.link;
}
It should be:
public Node(String item, Node link) {
this.item = item;
this.link = link;
}
More importantly, you should be debugging all of this as you go along
Related
I'm doing a dictionary system for my school assignment. The idea that I'm trying to do is to store every single word and its definitions in a node and searching them using a binary search tree.
But there has an issue that occurred. When I add a word and definition in a node in the linked list, the wordList() method returns the last node that I've entered. I think I am having trouble implementing and linking the nodes. Could you please help me? (Note: Vocab is my test class)
public class Node {
private static String word;
private static String definition;
private Node link;
public Node() {
link = null;
word = null;
}
public Node(String newWord) {
setWord(newWord);
link = null;
}
public Node(String newWord, Node linkValue) {
setWord(newWord);
link = linkValue;
}
public Node(String newWord, String newDefinition, Node linkValue) {
setWord(newWord, newDefinition);
link = linkValue;
}
public Node(String newWord, String newDefinition) {
setWord(newWord, newDefinition);
}
#Override
public String toString() {
return "Node [word=" + word + ", link=" + link + "]";
}
public static String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public static String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public void setWord(String word, String definition) {
this.word = word;
this.definition = definition;
}
public Node getLink() {
return link;
}
public void setLink(Node link) {
this.link = link;
}
}
public class LinkedList {
protected static Node first;
private Node last;
public LinkedList() {
super();
this.first = null;
this.last = null;
}
public LinkedList(String wordName, String wordDefinition, Node first2) {
// TODO Auto-generated constructor stub
}
public boolean isEmpty() {
return(first == null);
}
public void insert(String newWord, String newDefinition) {
if(isEmpty()) {
first= last= new Node(newWord, newDefinition, first);
}
else {
first = new Node(newWord, newDefinition, first);
}
}
public void wordList() {
Node current = first;
while(current != null) {
System.out.println(current.getWord());
current = current.getLink();
}
}
public static Node getFirst() {
return first;
}
public void setFirst(Node first) {
this.first = first;
}
public Node getLast() {
return last;
}
public void setLast(Node last) {
this.last = last;
}
}
public class Vocab {
public static void main(String[] args) {
LinkedList dictionary = new LinkedList();
Node a = new Node("Assembly","A unit of fitted parts that naje yo a mechanism or machine, such as the headstock assemble of a lathe.");
dictionary.setFirst(a);
Node b = new Node("Boil","Agitation of a bath of metal caused by the liberation of a gas beneath its surface.");
a.setLink(b);
b.setLink(null);
dictionary.wordList();
}
}
If you want to use your LinkedList, use its methods rather than making the manipulations by hand:
LinkedList dictionary = new LinkedList();
// Node a = new Node("Assembly","A unit of fitted parts that naje yo a mechanism or machine, such as the headstock assemble of a lathe.");
dictionary.setFirst(a);
//Node b = new Node("Boil","Agitation of a bath of metal caused by the liberation of a gas beneath its surface.");
//a.setLink(b);
//b.setLink(null);
dictionary.wordList();
In the code above I have commented out all lines of code that go one level too deep. On the usage side you should never care that the Node class is used internally.
Have a look at LinkedList methods that will work for you. Then try to think of why when you are not using them you never alter the internal properties of the list, thus leaving it broken an half setup.
EDIT: By the way consider removing the setFirst and setLast methods that accept Node instances. They are only confusing you and should have never been there.
When I unit test my pop and peek methods for my MyStack class, I encounter a NullPointerException relating to the getData method of my node class.
I cannot tell why and I am wondering if anyone has any ideas on how to fix it and make it so that there is not a NullPointerException. I have tried editing how the node works and how getData itself works but cannot find a solution and since cannot figure out the problem. Any help would be very much appreciated
import java.io.*;
import java.util.*;
public class MyStack<E> implements StackInterface<E>
{
public Node<E> head;
public int nodeCount = 0;
public static void main(String args[]) {
}
public E peek() {
return head.getData();
}
public E pop() {
if (nodeCount == 0) {
throw new EmptyStackException();
}
E item = head.getData();
head = head.getNext();
nodeCount--;
return item;
}
public boolean empty() {
if (head == null && nodeCount == 0) {
return true;
} else {
return false;
}
}
public void push(E data) {
Node<E> head = new Node<E>(data);
nodeCount++;
}
public int search(Object o) {
int count = 0;
Node<E> current = new Node<E>(head.getData());
while (current.getData() != o) {
current.getNext();
count++;
}
return count;
}
}
public class Node<E>
{
public E data;
public Node<E> next;
// getters and setters
public Node(E data)
{
this.data = data;
this.next = null;
}
public E getData() {
return this.data;
}
public void setData(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
One problem is in your push method. There, you are not assigning the new head to the member variable defined at class-level. An updated push method could look like this:
public void push(E data) {
Node<E> newHead = new Node<>(data);
newHead.setNext(head);
head = newHead;
nodeCount++;
}
In peek you should check if the stack is empty before trying to access getData():
public E peek() {
if (empty()) {
throw new EmptyStackException();
}
return head.getData();
}
Another NullPointerException happens in the search method where head.getData() is null for an empty stack. Furthermore, this method does not report the correct position of an item on the stack. I won't go into details in this answer as you have already asked a separate question.
I highly encourage to look into how to use a debugger to step through your code. Thereby, you can execute your program line by line and see where it is deviating from what you expect. Debugging is an essential skill as a programmer. Here are three resources:
IntelliJ IDEA Tutorial: Debug your first Java application
Eclipse Beginner’s Guide to Quick Start Debugging
Java Debugging with Eclipse - Tutorial
I need to implement a Node class, where the basic methods are: getItem(), getNext(), setItem() and setNext(). I want the nodes to be able to store at least the default integer range in Java as the “item”; the “next” should be a reference or pointer to the next Node in a linked list, or the special Node NIL if this is the last node in the list.I also want to implement a two-argument constructor which initializes instances with the given item (first argument) and next node (second argument) , I've kind of hit a brick wall and need some guidance about implementing this , any ideas ?
I have this so far:
class Node {
public Node(Object o, Node n) {
}
public static final Node NIL = new Node(Node.NIL, Node.NIL);
public Object getItem() {
return null;
}
public Node getNext() {
return null;
}
public void setItem(Object o) {
}
public void setNext(Node n) {
}
}
While implementing the custom LinkedList/Tree, we need Node. Here is demo of creating Node and LinkedList. I have not put in all the logic. Just basic skeleton is here and you can then add more on yourself.
I can give you a quick hint on how to do that:
Class Node{
//these are private class attributes, you need getter and setter to alter them.
private int item;
private Node nextNode;
//this is a constructor with a parameter
public Node(int item)
{
this.item = item;
this.nextNode = null;
}
// a setter for your item
public void setItem(int newItem)
{
this.item = newItem;
}
// this is a getter for your item
public int getItem()
{
return this.item;
}
}
You can create a Node object by calling:
Node newNode = Node(2);
This is not a complete solution for your problem, the two parameter constructor and the last node link are missing, but this should lead you in the correct direction.
Below is a simple example of the Node implementation, (i renamed Item to Value for readability purpose). It has to be implemented somehow like this, because methods signatures seems to be imposed to you. But keep in mind that this is definely not the best way to implement a LinkedList.
public class Node {
public static final Node NIL = null;
private Integer value;
private Integer next;
public Node(Integer value, Node next) {
this.value = value;
this.next = next;
}
public Integer getValue() {
return this.value;
}
public Node getNext() {
return this.next;
}
public void setValue(Integer value) {
this.value = value;
}
public void setNext(Node next) {
this.next = next;
}
public boolean isLastNode() {
return this.next == Node.NIL || Node;
}
}
public class App {
public static void main(String[] args) {
Node lastNode = new Node(92, Node.NIL);
Node secondNode = new Node(64, lastNode);
Node firstNode = new Node(42, secondNode);
Node iterator = firstNode;
do () {
System.out.println("node value : " + iterator.getValue());
iterator = iterator.getNext();
} while (iterator == null || !iterator.isLastNode());
}
}
The node class that will be implemented changes according to the linked list you want to implement. If the linked list you are going to implement is circular, then you could just do the following:
public class Node {
int data;
Node next = null;
public Node(int data){
this.data = data;
}
}
Then how are you going to implement the next node?
You are going to do it in the add method of the circularLinkedList class. You can do it as follows:
import java.util.*;
public class CircularLinkedList {
public CircularLinkedList() {}
public Node head = null;
public Node tail = null;
public void add(int data) {
Node newNode = new Node(data);
if(head == null) {
head = newNode;
}
else {
tail.next = newNode;
}
tail = newNode;
tail.next = head;
}
public void displayList() {
System.out.println("Nodes of the circular linked list: ");
Node current = head;
if(head == null) {
System.out.println("Empty list...");
}
else {
do {
System.out.print(" " + current.data);
current = current.next;
}while(current != head);
System.out.println();
}
}
}
Recently,I'm learing the Algorithms 4th,when I come to solve the problem that
Create a new constructor for the linked-list implementation of Stack.java so that Stack t = new Stack(s) makes t reference a new and independent copy of the stack s.
Here is the Stack.java
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Stack<Item> implements Iterable<Item> {
private Node<Item> first; // top of stack
private int n; // size of the stack
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
/**
* Initializes an empty stack.
*/
public Stack() {
first = null;
n = 0;
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void push(Item item) {
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
n++;
}
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item; // save item to return
first = first.next; // delete first node
n--;
return item; // return the saved item
}
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current;
public ListIterator(Node<Item> first) {
current = first;
}
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
The answer of Recursive solution is that create a copy constructor for a linked list starting at a given Node and use this to create the new stack.
Node(Node x) {
item = x.item;
if (x.next != null) next = new Node(x.next);
}
public Stack(Stack<Item> s) { first = new Node(s.first); }
But what make me confused is how can I combine the above code to the Stack.java as its constuctor,how can I handle the Node? to create a new class Node??May someone could hep me:)
You don't need to create a new class Node. The Node is the same for the old stack and the new stack 't'.
Currently you have one constructor in your Stack class public Stack(). You need to make another one that accepts a Stack, as you've done in your example, which then calls a method that copies the old elements to the new stack (recursively or iteratively). It sounds like homework so I don't think any code is appropriate (not sure of the rules in that regard).
Here is the code fragment I hava solved my problem
private class Node{
Item item;
Node next;
Node() { } //default constructor Node
Node(Node x){
item=x.item;
if(x.next!=null) next=new Node(x.next);
}
}
public Stack(){ //default constructor Stack
first=null;
N=0;
}
public Stack(Stack<Item> s) {first=new Node(s.first); }
I am new to Generics in java and I really need help in this code
it is not compiling i dont know why!
The stack class is:
public class GenericStack<Item>{
public class Stack {
private Node first=null;
private class Node {
Item item;
Node next;
}
public boolean IsEmpty()
{
return first==null;
}
public void push (Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Item pop ()
{
Item item=first.item;
first=first.next;
return item;
}
}
}
and here is the main
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
GenericStack<Integer> ob = new GenericStack<Integer>();
ob.push(5);
obpush(10);
ob.push(15);
while (!ob.IsEmpty())
{
int x=ob.pop();
StdOut.print(x);
}
}
}
now the error is:
The method push(int) isn't defined for the type GenericStack<Integer>
Where did i go wrong?! can anyone explain please to me
Thank you in advance
Your GenericStack class has no methods. Get rid of the nested class structure and use the generic type parameter for Stack directly:
public class Stack<Item> {
private Node first=null;
private class Node {
Item item;
Node next;
}
public boolean IsEmpty()
{
return first==null;
}
public void push (Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Item pop ()
{
Item item=first.item;
first=first.next;
return item;
}
}
class GenericStack<Item>{
class Stack {
private Node first=null;
private class Node {
Item item;
Node next;
}
public boolean IsEmpty()
{
return first==null;
}
public void push (Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Item pop ()
{
Item item=first.item;
first=first.next;
return item;
}
}
}
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
GenericStack<Integer> ob = new GenericStack<Integer>();
GenericStack<Integer>.Stack st=ob.new Stack();
st.push(5);
st.push(10);
st.push(15);
while (!st.IsEmpty())
{
int x=st.pop();
// StdOut.print(x);
System.out.println(x);
}
}
}
You are calling methods of the inner class. So that using object of outer class you cannot directly call the methods of the inner class. See above code for that.
Hope this helps.
Because method push is defined in class GenericStack.Stack, not GenericStack. To make it work replace
GenericStack<Integer> ob = new GenericStack<Integer> ();
with
GenericStack<Integer>.Stack ob = new GenericStack.Stack ();
The main issue with your code is that you mixed 2 public classes, just changed a little your code, have fun !!
GenericStack.java
public class GenericStack<Item> {
private Node first = null;
private class Node {
Item item;
Node next;
}
public boolean IsEmpty() {
return first == null;
}
public void push(Item item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Item pop() {
Item item = first.item;
first = first.next;
return item;
}
}
TestGenericStack.java
public class TestGenericStack {
public static void main(String[] args) {
GenericStack<Integer> ob = new GenericStack<Integer>();
ob.push(5);
ob.push(10);
ob.push(15);
while (!ob.IsEmpty()) {
int x = ob.pop();
System.out.println(x);
}
}
}
Get rid of the extra coating of class Stack from GenericStack.
Thanks!