Push method for Stack with Nodes - java

I am having trouble doing a homework assignment involving stacks and nodes in Java. I understand the concept of Stacks but am confused with Nodes. The assignment is to make a program using Stacks (Not java.util.Stack) that checks a mathematical expression for correct pairs of (), [], and {}s. We already have the Node program.
So basically my problem is I would like some help completing the Push Method of my PStack class.
PStack.java
class PStack {
private Node top;
public PStack() {
top=null;
}
public boolean isEmpty() {
return top==null;
}
public int pop() {
Node top1 = top;
top = top.getNext();
return top1.getData();
}
public void push(Node n) {
}
public int peek() {
return top.getData();
}
}
Node.java
public class Node {
private int data;
private Node nextnode;
public Node(int intial) {
data = intial;
nextnode = null;
}
public int getData() {
return data;
}
public Node getNext() {
return nextnode;
}
public void setData(int newdata) {
data = newdata;
}
public void setNode(Node next1node) {
nextnode = next1node;
}
}
I tried:
public void push(Node n) {
Node next = n;
top.getNext().setNode(n);
}
Result:
Exception in thread "main" java.lang.NullPointerException
at javaclass.stack.pStack.push(pStack.java:24)
at javaclass.stack.StackDriver.main(StackDriver.java:17)

public void push(Node n) {
n.setNode(top);
top = n;
}
Edit:
BTW, this is an odd implementation of a stack. It looks like it wants to be a stack of int primitives. Both peek() and pop() return an int. But then push takes an argument that should be an internal construct of the stack itself. It shouldn't take a Node object as an argument. It should take an int argument and wrap it with the Node object internally.
Also, Node.setNode should be named Node.setNext. It's just more consistent with what you are doing. A linked list node has a "next" member and a double linked list node has "next" and "previous" members. The getters and setters of the node object should be appropriately named for those members.
Like this:
PStack.java
public class PStack {
private Node top;
public boolean isEmpty() {
return top==null;
}
public int pop() {
Node top1 = top;
top = top.getNext();
return top1.getData();
}
public void push(int data) {
Node newtop = new Node(data);
newtop.setNext(top);
top = newtop;
}
public int peek() {
return top.getData();
}
}
Node.java
public class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}

Related

Java priority queue that extends comparable?

I am working on a class assignment and I don't quite understand how to use comparator in the way the assignment is asking.
The assignment reads:
"Complete the Priority Queue class
Your Priority Queue must use an anonymous function to decide priority
It must take the Function interface as a parameter to the constructor
You should still have the default constructor – and if no function is provide use the compareTo function of the class"
This is the class that I am working on...
public class PriorityQueue <Item extends Comparable<Item>> {
public PriorityQueue()
{
}
public PriorityQueue(Comparator<Item> compare )
{
}
private int size = 0;
private Node<Item> head = null;
private Comparator<Item> compare ;
private static class Node<Item>
{
private Item data;
private Node<Item> next;
public Node(Item data, Node<Item> next)
{
this.data = data;
this.next = next;
}
public Node(Item data)
{
this.data = data;
this.next = null;
}
public Node()
{
this.data = null;
this.next = null;
}
}
#Override
public int size() {
return size;
}
#Override
public Item dequeue() {
// TODO Auto-generated method stub
return null;
}
#Override
public void enqueue(Item item) {
Node<Item> curr = head;
Node<Item> prev = curr;
if (isEmpty())
{
head = new Node<Item>(item,null);
}
else
{
while (curr != null)
{
prev = curr;
curr = curr.next;
}
prev.next = new Node<Item>(item, curr);
}
size++;
}
#Override
public boolean isEmpty() {
return size == 0;
}
#Override
public void printQueue() {
Node<Item> curr = head;
while (curr != null)
{
System.out.println(curr.data);
curr = curr.next;
}
}
}
This is the process class that the queue will contain...
public class Process implements Comparable<Process> {
private ProcessPriorty priority;
private String name;
public Process(ProcessPriorty priority, String name) {
super();
this.priority = priority;
this.name = name;
}
public void setPriority(ProcessPriorty priority) {
this.priority = priority;
}
#Override
public String toString() {
return name + "... Priority = " + priority + ".";
}
public String getName() {
return name;
}
public ProcessPriorty getPriority() {
return priority;
}
#Override
public int compareTo(Process other) {
if(other == null)
{
return 1;
}
return this.priority.compareTo(other.priority) ;
}
}
I understand the concept of a queue and have even coded the enqueue method to work as a simple queue that inserts the items as they come in. The problem I am coming across is comparing the nodes within that method to sort the list by priority at insertion. Which I believe relates back to those three directions of the assignment. So, what am I suppose to do with the constructors, the Comparator variable, and how do I make it default to compareTo?
Well since you have a reference to the head of the queue, its pretty simple from there. You have 2 cases -
compare != null
compare == null
In the first case, you are interested in Comparator::compareTo. From the definition of a priority queue, all you have to do is traverse the queue beginning from head, and as soon as the item in enqueue(Item item) is greater than the current element in the traversal, you insert item before element. You'll use compare.compareTo(item, element) to determine their order.
In the second case you'll simply use item.compareTo(element) to make the above stated comparison, the traversal and insertion will be the same.

When I pass the Node variable that is "top" inside the node objects ? does it help it to point the previous data?

I am writing a code to practice some linked list example with basics but came across a problem when in linked list class in voidadd method what does it means when I pass the Node variable that is "top" inside the node objects ? does it help it to point the previous data? i have indicated the part that refers to my question
public class Node
{
private int data;
private Node nextNode;
public Node(int dataP , Node nextNodeP)
{
data = dataP;nextNode = nextNodeP;
}
public int getData()
{
return data;
}
public Node getNextNode()
{
return nextNode;
}
public void setData(int newData) //to replace the value of some notes [12| ] --> [120| ]
{
data = newData;
}
public void setNext(Node newNextNode) // pointing to top ---> [120| ] ---> [last | null]
{
nextNode = newNextNode;
}
}
public class LinkedList {
private Node top;
private int size;
public LinkedList() {
top = null;
size = 0;
}
public int getSize() {
return size;
}
public void addNode(int newData) {
Node temp = new Node(newData, top); //question
top = temp; //points to the same
size++;
}
}
Define a node at its own class.
Here is a simple example :
public class LinkedList {
private Node first,last;
private int size ;
//adds node as last. not null safe
public void addNode(Node node) {
if(first == null) {
node.setParent(null);
first = node;
last = node;
}else {
node.setParent(last);
last = node;
}
size++;
}
public Node getFirst() {return first;}
public Node getLast() { return last; }
public int getSize() {return size;}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addNode(new Node(0,null));
list.addNode(new Node(1,null));
list.addNode(new Node(2,null));
list.addNode(new Node(3,null));
Node node = list.getLast();
System.out.println("list has "+ list.size + " nodes:");
while(node != null) {
System.out.println(node);
node = node.getParent();
}
}
}
class Node{
private int data;
private Node parent;
Node(int nodeData, Node parent) {
data = nodeData;
this.parent = parent;
}
public int getData() { return data;}
public void setData(int data) { this.data = data; }
public Node getParent() {return parent; }
public void setParent(Node parent) {this.parent = parent;}
#Override
public String toString() {return "Node "+getData() +" parent:"+ getParent();}
}

Understanding doubly linked circular list

I have an assignment in my CS class about circular doubly linked lists. We are given a Node class that sets up the links and such.
public class Node {
private Node previous, next;
private Object data;
public Node(Object data) {
this.data = data;
}
public Node() {
}
public Node(Object data, Node previous, Node next) {
this.previous = previous;
this.next = next;
this.data = data;
}
public Node getPrevious() {
return previous;
}
public void setPrevious(Node previous) {
this.previous = previous;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
and we are tasked with implementing a few methods. In the list class there is one Node created called 'base'
public class DList {
private Node base;
public DList() {
}
all of the methods require some form of traversing the list. From what I understand setting up a temp node to be equal to base.getNext() will give me the first node of the list and testing if temp != base will be my check for reaching the end of the list since the base node serves as an anchor for the rest of the nodes (if my understanding is correct).
However, when I try to do bits of code such as:
public int size() {
int count = 0;
if (base.getNext() == base)
return count;
else {
Node temp = base.getNext();
while (temp != base) {
temp = temp.getNext();
count++;
}
}
return count;
}
I get a null pointer exception at the line where I say Node temp = base.getNext(); and for the life of me I cannot understand why, because like I said earlier I thought that base.getNext() would be the first element of my list.
There is no need for a dummy base node. In that case base initially is null.
In that case:
public int size() {
int count = 0;
if (base != null) {
Node temp = base;
do {
temp = temp.getNext();
count++;
} while (temp != base);
}
return count;
}

Remove method for Stack in Java

I am struggling to figure this out - I need to implement a method:
public int remove(int n)
where I remove the top most n entries from my stack. Any suggestions on where I can start to tackle this would be greatly appreciated.
Here is the code provided where I need to implement this remove() method.
public class LinkedStack<T> implements StackInterface<T>
{
private Node topNode; // references the first node in the chain
public LinkedStack()
{
topNode = null;
} // end default constructor
public void push(T newEntry)
{
Node newNode = new Node(newEntry, topNode); topNode = newNode;
} // end push
public T peek()
{
T top = null;
if (topNode != null)
top = topNode.getData();
return top;
} // end peek
public T pop()
{
T top = peek();
if (topNode != null)
topNode = topNode.getNextNode();
return top;
} // end pop
public boolean isEmpty() {
return topNode == null;
}
public void clear() {
topNode = null;
}
private class Node
{
private T data; // entry in stack
private Node next; // link to next node
private Node(T dataPortion)
{
this(dataPortion, null);
} // end constructor
private Node(T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode;
} // end constructor
private T getData()
{
return data;
} // end getData
private void setData(T newData)
{
data = newData;
} // end setData
private Node getNextNode()
{
return next;
} // end getNextNode
private void setNextNode(Node nextNode)
{
next = nextNode;
} // end setNextNode
} // end Node
} // end LinkedStack
The trivial solution is just to call this.pop() n times. For this, you need to use a loop.
Seems like your homework, so I'm not going to show a code example.

java.lang.NullPointerException in my custom class

I wish to implement a Queue based in a simple linked list class, without using java.util.
When I call the addEnd method in List class through enqueue method, I receive a java.lang.NullPointerException, though I expect the second element.
Which solution can I take?
The node class
public class Node {
private int value;
private Node next;
public Node(int val) {
value = val;
}
public Node(int val, Node next) {
value = val;
this.next=next;
}
public Node(Node next) {
this.next=next;
}
public int getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public void displayNode() {
System.out.print(" "+value+" ");
}
}
My interface
public interface MyQueue {
void enqueue(int oVal);
int dequeue();
}
The List
public class List {
private Node first;
private Node last;
private int counter;
public List() {
first = null;
last = null;
}
public boolean isEmpty() {
return first==null;
}
public void addEnd(int val) {
Node n1 = new Node(val);
if( isEmpty() ) {
first = n1;
} else {
last.setNext(n1);
last = n1;
}
}
public int deleteStart() {
int temp = first.getValue();
if(first.getNext() == null){
last = null;
first = first.getNext();
}
return temp;
}
public void displayList() {
Node current = first;
while(current != null) {
current.displayNode();
current = current.getNext();
}
System.out.println("");
}
public int size() {
return counter;
}
}
The Queue
public class Queue implements MyQueue {
private List listQ;
public Queue() {
listQ = new List();
}
public boolean isEmpty() {
return listQ.isEmpty();
}
public void enqueue(int oVal) {
listQ.addEnd(oVal);
}
public int dequeue() {
return listQ.deleteStart();
}
public void displayQueue() {
System.out.print("Queue ");
listQ.displayQueue();
}
}
public class App {
public static void main(String[] args) {
Queue q1 = new Queue();
System.out.println("Two insertions");
q1.enqueue(4);
q1.enqueue(64);
q1.displayQueue();
System.out.println("Insert at the end : ");
q1.enqueue(23);
q1.displayQueue();
System.out.println("Delete an element at the begining of the queue");
q1.dequeue();
q1.displayQueue();
}
}
What #pens-fan-69 said is true. I'd like to add on to that. In order to make your code work, all you have to do is make sure last is set to first during the first insert:
public void addEnd(int val) {
Node n1 = new Node(val);
if( isEmpty() ) {
first=last=n1;
} else {
last.setNext(n1);
last = n1;
}
}
I tried running the code in online compiler and it works: http://goo.gl/99FyfY
You need to set the last reference when inserting to the empty list. The NullPointerException is because you use last before ever setting it.

Categories

Resources