Simple Stack, how to initialize Node at 0 instead of null - java

I am trying to implement a very simple stack, however, it seems that I need to use a node for this. I have the below which compiles and works fine, however, it throws a lot of errors until someone makes the first push. I am in a situation where I cannot control what is in the consumer's main method, so I think it would be best to avoid these errors and just initialize a new stack object with an initial value of zero. Unfortunately, I cannot figure out just how to do that. Would anyone here be able to advise me?
import java.util.*;
public class StackQ {
Node top;
public StackQ() {
top=null;
}
class Node {
public int x = 0;
public Node next;
Node(int d) {x=d; next=null;}
public int getData() {return x;}
}
public int pop() {
if(top!=null) {
int item = top.x;
top = top.next;
return item;
}
return -1;
}
public void push(int x) {
Node t = new Node(x);
t.next = this.top;
this.top = t;
}
public int top() {
if (top == null) throw new EmptyStackException();
return top.x;
}
public static void main(String[] args) {
StackQ mainStack = new StackQ();
}
}

If they're using top() without putting anything in the stack, they are using your stack wrong. Seriously, they should be getting an exception. It's up to them to not use your stack that way, and it's up to them to properly handle that exception.
But if you really wanted to always start your stack with a 0 in it (which, to be perfectly clear, I am advising against doing) just put that in your constructor.
public StackQ() {
top=new Node(0);
}

Related

NullPointerException error when unit testing

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

Implementation of ArrayList using a LinkedList

I need to implement both a Queue and ArrayList by using an internal LinkedList. I created my DoublyLinkedList class and was able to implement it into my queue with no problem. The problem I am running into is that to add or delete to/from the ArrayList, the add/delete methods take in a integer for the index and an object/element. All my methods inside my DoublyLinkedList class take in either elements and/or Nodes.
My question is this, how can I implement my DoublyLinkedList methods inside my ArrayList when my DLL class doesn't take any int values in.
I want to be able to add or delete the node by using the index, but I can't. Realistically, I would want something like list.addAfter(I) without I being an integer.
Note: The goal of this assignment is to implement ADTs, so I can't modify the method signatures of the ArrayList ADT.
DoublyLinedList Class
public class DoublyLinkedList<E> {
private Node<E> head;
private Node<E> tail;
private int size;
public DoublyLinkedList() {
this.head = new Node<E>(null, null, null);
this.tail = new Node<E>(null, null, null);
this.size = 0;
head.setNext(tail);
tail.setPrev(head);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public Node<E> getPrev(Node<E> n) {
return n.getPrev();
}
public Node<E> getNext(Node<E> n) {
return n.getNext();
}
public Node<E> getFirst() {
return head.getNext();
}
public Node<E> getLast() {
return tail.getPrev();
}
public E remove(Node<E> c) {
Node<E> a = c.getPrev();
Node<E> b = c.getNext();
b.setNext(a);
a.setPrev(b);
c.setNext(null);
c.setPrev(null);
size--;
return c.getElement();
}
public E removeFirst() {
return remove(head.getNext()); // first element is beyond header
}
public E removeLast() {
return remove(tail.getPrev());
}
public void addBefore(Node<E> node, E e) {
Node<E> prev = getPrev(node);
Node<E> n = new Node<E>(e, prev, node);
node.setPrev(n);
prev.setNext(n);
size++;
}
public void addFirst(E e) {
addAfter(head, e);
}
public void addLast(E e) {
addBefore(tail, e);
}
public void addAfter(Node<E> node, E e) {
Node<E> next = getNext(node);
Node<E> n = new Node<E>(e, node, next);
node.setNext(n);
next.setPrev(n);
size++;
}
}
LArrayList class (my Arraylist implementation)
public class LArrayList implements List {
private DoublyLinkedList list;
private int size;
public LArrayList() {
this.list = new DoublyLinkedList();
this.size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void add(int I, Object e) throws IndexOutOfBoundsException {
if (isEmpty()) {
list.addFirst(e);
}
// HERE IS MY CONCERN. THESE FOUR METHODS ALL TAKE IN INT VALUES WHILE
// NON OF MY DLL METHODS DO!
}
public Object get(int i) throws IndexOutOfBoundsException {
return null;
}
public Object remove(int i) throws IndexOutOfBoundsException {
return null;
}
public Object set(int I, Object e) throws IndexOutOfBoundsException {
return null;
}
}
It seems like a fairly easy thing to do - just use the API exposed by your LinkedList and add some logic to it. Here is the bit you are missing
if (list.size() < I) {
throw new IndexOutOfBoundsException()
}
//get a starting point
Node node = list.getFirst();
//loop until you get to the specified position
while(I-- > 0) {
node = list.getNext(node);
}
//now node points at the node in position I - insert the new
//node before it to comply with the List interface
list.addBefore(node, e);
this.size++;
I do have to note that your LinkedList implementation can be improved - first of all, the getPrev() getNext() addBefore() and addAfter() should be static, as you shouldn't have to use a LinkedList instance to call them. However, it would be even better if the methods were actually methods in Node, because that way the traversal and usage of the LinkedList would be way more easy. Here is how the above code would look like if the methods were in Node:
if (list.size() < I) {
throw new IndexOutOfBoundsException()
}
//get a starting point
Node node = list.getFirst();
//loop until you get to the specified position
while(I-- > 0) {
node = node.getNext();
}
//now node points at the node in position I - insert the new
//node before it to comply with the List interface
node.addBefore(e);
this.size++;
You pretty much do not need the list at all - certainly you don't need to just pass extra parameters to some functions. You can still keep the (hopefully static) methods in Linked list that do the same thing, but they'd just be proxies for the Node implementation of the methods, e.g.:
public static void addAfter(Node<E> node, E e) {
node.addAfter(e);
}
I am not sure if you will need these methods in LinkedList but they can certainly be there for "backwards compliance", if you will.
EDIT Forgot to mention - the fist bit of code is the implementation for add(), I am sure you can work out the rest, as they'd do the same thing.
public Object get(int i) throws IndexOutOfBoundsException {
if(list.size()<=i) throw new IndexOutOfBoundsException();
Node current = list.getFirst();
for(int x = 0; x<=i; x++){
if(x == i) return current.getElement();//Change this behaviour for remove and set
current = current.getNext();
}
}

Iterable interface implementation

Can someone tell me if my implementation for Stack is right?
class LevelIter<Node> implements Iterable<Node> {
Stack<Node> s = null;
public LevelIter(Stack<Node> s) {
this.s = s;
}
public Iterator<Node> iterator(){
Iterator<Node> it = new Iterator<Node>() {
private int index = 0;
#Override
public boolean hasNext(){
return (index < s.size() && !s.isEmpty());
}
#Override
public Integer next(){
return (Integer) (s.pop()).data;
}
#Override
public void remove(){
s.remove();
}
};
return it;
}
}
Where Node is a node in a binary tree -
class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
this.left = null;
this.right = null;
}
}
And I am calling in the main as --
LevelIter<Node> l = new LevelIter<Node>(s);
for(int n:l){
System.out.println(n);
}
An iterator probably shouldn't modify a shared data structure. Your constructor should copy the passed stack so it doesn't pop elements from it.
Pass by reference and pass by value are tricky subjects to master. You're actually copying the reference in your code, so the LevelIter's Stack object is going to be the same as whatever stack is passed in. This means when you iterate using a LevelIter, its going to empty whatever stack LevelIter was constructed with. This is probably undesirable and is the reason I suggest the following:
class LevelIter<Node> implements Iterable<Node> {
Stack<Node> s = null;
public LevelIter(Stack<Node> s) {
this.s = (Stack)s.clone();
}
//rest is the same.
}
The rest of your code looks fine to me. Best way to make sure your code works is to test it though. Create a class which just tests this iterator. Make sure its functioning the way you expect.

Doubly linked lists

I have an assignment that I am terribly lost on involving doubly linked lists (note, we are supposed to create it from scratch, not using built-in API's). The program is supposed to keep track of credit cards basically. My professor wants us to use doubly-linked lists to accomplish this. The problem is, the book does not go into detail on the subject (doesn't even show pseudo code involving doubly linked lists), it merely describes what a doubly linked list is and then talks with pictures and no code in a small paragraph. But anyway, I'm done complaining. I understand perfectly well how to create a node class and how it works. The problem is how do I use the nodes to create the list? Here is what I have so far.
public class CardInfo
{
private String name;
private String cardVendor;
private String dateOpened;
private double lastBalance;
private int accountStatus;
private final int MAX_NAME_LENGTH = 25;
private final int MAX_VENDOR_LENGTH = 15;
CardInfo()
{
}
CardInfo(String n, String v, String d, double b, int s)
{
setName(n);
setCardVendor(v);
setDateOpened(d);
setLastBalance(b);
setAccountStatus(s);
}
public String getName()
{
return name;
}
public String getCardVendor()
{
return cardVendor;
}
public String getDateOpened()
{
return dateOpened;
}
public double getLastBalance()
{
return lastBalance;
}
public int getAccountStatus()
{
return accountStatus;
}
public void setName(String n)
{
if (n.length() > MAX_NAME_LENGTH)
throw new IllegalArgumentException("Too Many Characters");
else
name = n;
}
public void setCardVendor(String v)
{
if (v.length() > MAX_VENDOR_LENGTH)
throw new IllegalArgumentException("Too Many Characters");
else
cardVendor = v;
}
public void setDateOpened(String d)
{
dateOpened = d;
}
public void setLastBalance(double b)
{
lastBalance = b;
}
public void setAccountStatus(int s)
{
accountStatus = s;
}
public String toString()
{
return String.format("%-25s %-15s $%-s %-s %-s",
name, cardVendor, lastBalance, dateOpened, accountStatus);
}
}
public class CardInfoNode
{
CardInfo thisCard;
CardInfoNode next;
CardInfoNode prev;
CardInfoNode()
{
}
public void setCardInfo(CardInfo info)
{
thisCard.setName(info.getName());
thisCard.setCardVendor(info.getCardVendor());
thisCard.setLastBalance(info.getLastBalance());
thisCard.setDateOpened(info.getDateOpened());
thisCard.setAccountStatus(info.getAccountStatus());
}
public CardInfo getInfo()
{
return thisCard;
}
public void setNext(CardInfoNode node)
{
next = node;
}
public void setPrev(CardInfoNode node)
{
prev = node;
}
public CardInfoNode getNext()
{
return next;
}
public CardInfoNode getPrev()
{
return prev;
}
}
public class CardList
{
CardInfoNode head;
CardInfoNode current;
CardInfoNode tail;
CardList()
{
head = current = tail = null;
}
public void insertCardInfo(CardInfo info)
{
if(head == null)
{
head = new CardInfoNode();
head.setCardInfo(info);
head.setNext(tail);
tail.setPrev(node) // here lies the problem. tail must be set to something
// to make it doubly-linked. but tail is null since it's
// and end point of the list.
}
}
}
Here is the assignment itself if it helps to clarify what is required and more importantly, the parts I'm not understanding. Thanks
https://docs.google.com/open?id=0B3vVwsO0eQRaQlRSZG95eXlPcVE
if(head == null)
{
head = new CardInfoNode();
head.setCardInfo(info);
head.setNext(tail);
tail.setPrev(node) // here lies the problem. tail must be set to something
// to make it doubly-linked. but tail is null since it's
// and end point of the list.
}
the above code is for when u not have any nodes in list, here u r going to add nodes to ur list.I.e. ist node to list
here u r pointing head & tail to same node
I assume CardList is meant to encapsulate the actual doubly-linked-list implementation.
Consider the base case of a DLL with only a single node: the node's prev and next references will be null (or itself). The list's encapsulation's head and tail references will both be the single node (as the node is both the start and end of the list). What's so difficult to understand about that?
NB: Assuming that CardList is an encapsulation of the DLL structure (rather than an operation) there's no reason for it to have a CardInfoNode current field, as that kind of state information is only useful to algorithms that work on the structure, which would be maintaining that themselves (it also makes your class thread-unsafe).

Implementing stack using linked lists

What's the best way to implement a stack using linked lists in Java?
EDIT: I would define best as most efficient using clean code. I have already used an array to implement a stack, but am not familiar with link lists so was wondering if anyone could help me implement something similar to below:
public class StackArray{
private Object [] objArray;
private int stackSize;
public StackArray(){
objArray = new Object[50];
stackSize = 0;
}
public StackArray(int size){
objArray = new Object[size];
stackSize = 0;
}
//public interface methods - push, pop, top, empty & clear
public void push(Object o)throws StackArrayException{
if(stackSize < objArray.length){
objArray[stackSize] = o;
stackSize ++;
}else{
throw new StackArrayException("Stack Overflow");
}
}
public Object pop()throws StackArrayException{
if(stackSize != 0){
stackSize--;
return(objArray[stackSize]);
}else{
throw new StackArrayException("Stack Underflow");
}
}
public void top() throws StackArrayException{
if(stackSize != 0){
return(objArray[stackSize-1]);
}else{
throw new StackArrayException("Stack Underflow");
}
}
public boolean empty(){
return (stackSize == 0):
}
public void clear(){
stackSize = 0;
}
}
EDIT: Here is the linked list implementation if anyone is interested..
public class StackList{
private Node listHead;
protected class Node{
protected Object datum;
protected Node next;
public Node(Object o, Node n){
datum = o;
next = n;
}
public StackList(){
listHead = null;
}
//public interface methods - push pop top empty clear
public void push(Object o){
listHead = new Node(o, listHead);
}
public Object pop() throws StackListException{
if(listHead!=null){
Object top = listHead.datum;
listHead = listHead.next;
return top;
}else{
throw new StackListException("Stack Underflow");
}
}
public Object top()throws StackListException{
if(listHead != null){
return(listHead.datum);
}else{
throw new StackListException("Stack Underflow");
}
}
public boolean empty(){
return (listHead == null);
}
public void clear(){
listHead = null;
}
}
Assuming you genuinely want to do this from scratch rather than using one of the perfectly good existing stack implementations then I would recommend:
Create a "MyStack< T >" class which implements any interfaces you want (perhaps List < T >?)
Within MyStack create a "private static final class Node< T >" inner class for each linked list item. Each node contains a reference to an object of type T and a reference to a "next" Node.
Add a "topOfStack" Node reference to MyStack.
The push and pop operations just need to operate on this topOfStack Node. If it is null, the Stack is empty. I'd suggest using the same method signatures and semantics as the standard Java stack, to avoid later confusion.....
Finally implement any other methods you need. For bonus points, implement "Iterable< T >" in such a way that it remembers the immutable state of the stack at the moment the iterator is created without any extra storage allocations (this is possible :-) )
Why don't you just use the Stack implementation already there?
Or better (because it really a linked list, its fast, and its thread safe): LinkedBlockingDeque
If you're talking about a single linked list (a node has a reference to the next object, but not the previous one), then the class would look something like this :
public class LinkedListStack {
private LinkedListNode first = null;
private LinkedListNode last = null;
private int length = 0;
public LinkedListStack() {}
public LinkedListStack(LinkedListNode firstAndOnlyNode) {
this.first = firstAndOnlyNode;
this.last = firstAndOnlyNode;
this.length++;
}
public int getLength() {
return this.length;
}
public void addFirst(LinkedListNode aNode) {
aNode.setNext(this.first);
this.first = aNode;
}
}
public class LinkedListNode {
private Object content = null;
private LinkedListNote next = null;
public LinkedListNode(Object content) {
this.content = content;
}
public void setNext(LinkedListNode next) {
this.next = next;
}
public LinkedListNode getNext() {
return this.next;
}
public void setContent(Object content) {
this.content = content;
}
public Object getContent() {
return this.content;
}
}
Of course you will need to code the rest of the methods for it to work properly and effectively, but you've got the basics.
Hope this helps!
For implementing stack using using LinkedList- This StackLinkedList class internally maintains LinkedList reference.
StackLinkedList‘s push method internally calls linkedList’s insertFirst() method
public void push(int value){
linkedList.insertFirst(value);
}
StackLinkedList’s method internally calls linkedList’s deleteFirst() method
public void pop() throws StackEmptyException {
try{
linkedList.deleteFirst();
}catch(LinkedListEmptyException llee){
throw new StackEmptyException();
}
}
Full Program
/**
*Exception to indicate that LinkedList is empty.
*/
class LinkedListEmptyException extends RuntimeException{
public LinkedListEmptyException(){
super();
}
public LinkedListEmptyException(String message){
super(message);
}
}
/**
*Exception to indicate that Stack is empty.
*/
class StackEmptyException extends RuntimeException {
public StackEmptyException(){
super();
}
public StackEmptyException(String message){
super(message);
}
}
/**
*Node class, which holds data and contains next which points to next Node.
*/
class Node {
public int data; // data in Node.
public Node next; // points to next Node in list.
/**
* Constructor
*/
public Node(int data){
this.data = data;
}
/**
* Display Node's data
*/
public void displayNode() {
System.out.print( data + " ");
}
}
/**
* LinkedList class
*/
class LinkedList {
private Node first; // ref to first link on list
/**
* LinkedList constructor
*/
public LinkedList(){
first = null;
}
/**
* Insert New Node at first position
*/
public void insertFirst(int data) {
Node newNode = new Node(data); //Creation of New Node.
newNode.next = first; //newLink ---> old first
first = newNode; //first ---> newNode
}
/**
* Deletes first Node
*/
public Node deleteFirst()
{
if(first==null){ //means LinkedList in empty, throw exception.
throw new LinkedListEmptyException("LinkedList doesn't contain any Nodes.");
}
Node tempNode = first; // save reference to first Node in tempNode- so that we could return saved reference.
first = first.next; // delete first Node (make first point to second node)
return tempNode; // return tempNode (i.e. deleted Node)
}
/**
* Display LinkedList
*/
public void displayLinkedList() {
Node tempDisplay = first; // start at the beginning of linkedList
while (tempDisplay != null){ // Executes until we don't find end of list.
tempDisplay.displayNode();
tempDisplay = tempDisplay.next; // move to next Node
}
System.out.println();
}
}
/**
* For implementing stack using using LinkedList- This StackLinkedList class internally maintains LinkedList reference.
*/
class StackLinkedList{
LinkedList linkedList = new LinkedList(); // creation of Linked List
/**
* Push items in stack, it will put items on top of Stack.
*/
public void push(int value){
linkedList.insertFirst(value);
}
/**
* Pop items in stack, it will remove items from top of Stack.
*/
public void pop() throws StackEmptyException {
try{
linkedList.deleteFirst();
}catch(LinkedListEmptyException llee){
throw new StackEmptyException();
}
}
/**
* Display stack.
*/
public void displayStack() {
System.out.print("Displaying Stack > Top to Bottom : ");
linkedList.displayLinkedList();
}
}
/**
* Main class - To test LinkedList.
*/
public class StackLinkedListApp {
public static void main(String[] args) {
StackLinkedList stackLinkedList=new StackLinkedList();
stackLinkedList.push(39); //push node.
stackLinkedList.push(71); //push node.
stackLinkedList.push(11); //push node.
stackLinkedList.push(76); //push node.
stackLinkedList.displayStack(); // display LinkedList
stackLinkedList.pop(); //pop Node
stackLinkedList.pop(); //pop Node
stackLinkedList.displayStack(); //Again display LinkedList
}
}
OUTPUT
Displaying Stack > Top to Bottom : 76 11 71 39
Displaying Stack > Top to Bottom : 71 39
Courtesy : http://www.javamadesoeasy.com/2015/02/implement-stack-using-linked-list.html
Use the STL adapter std::stack. Why? Because the code you don't have to write is the fastest way to completion of your task. stack is well-tested, and likely to not need any attention from you. Why not? Because there are some special-purpose requirements needed by your code, undocumented here.
By default stack uses a deque double-ended queue, but it merely requires the underlying container to support "Back Insertion Sequence", also known as .push_back.
typedef std::stack< myType, std::list<myType> > myStackOfTypes;
Here is a tutorial implement using an array and linked list stack implementation.
It depends on the situation.
Array :- you can not resize it (fix size)
LinkedList :- it takes more memory than the array-based one because it wants to keep next node in memory.
I saw many stack implementation using LinkedList, At the end I understand what stack is.. and implemented stack by myself(for me it's clean and efficient). I hope you welcome new implementations. Here the code follows.
class Node
{
int data;
Node top;
public Node()
{
}
private Node(int data, Node top)
{
this.data = data;
this.top = top;
}
public boolean isEmpty()
{
return (top == null);
}
public boolean push(int data)
{
top = new Node(data, top);
return true;
}
public int pop()
{
if (top == null)
{
System.out.print("Stack underflow<-->");
return -1;
}
int e = top.data;
top = top.top;
return e;
}
}
And here the main class for it.
public class StackLinkedList
{
public static void main(String[] args)
{
Node stack = new Node();
System.out.println(stack.isEmpty());
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
System.out.println(stack.pop());
}
}

Categories