I am working on a Linked List implementation of a Stack, and seem to have what I need with only one error. I am inserting 3 strings, but before the 3rd string is popped, I get a NullPointerException.
In running debug I found that this missing value is being 'popped' off this list but it seems like it is not counted...meaning it is missing from the stack, not printed to the console, and the list does one more iteration at which point the NullPointerException is thrown because the last value was already popped. Can someone tell me how to get all of my values to print to console?
Here is my LinkedListStack Class:
public class LinkedListStack <T>{
private LinkedListStackNode<T> top;
public T data;
class LinkedListStackNode<T> {
private T data; //LINE 8
private LinkedListStackNode<T> next;
public LinkedListStackNode(T data, LinkedListStackNode<T> next) {
this.data = data;
this.next = next;
}
}
public void stack(){
top = null;
}
public boolean isEmpty(){
return top == null;
}
public void push (T t){
top = new LinkedListStackNode<T> (t, top);
}
public T pop (){
if (isEmpty()){
System.out.println("The stack is empty!");
}
else{
top = top.next;
}
return top.data; //Line 32
}
public T peek(){
if (isEmpty()){
System.out.println("Stack is Empty");
}
return top.data;
}
}
Here is my Main():
public class StacksAndQsMain {
public static void main(String[] args) {
...snipped code to condense (not part of this implementation)...
//LinkedList Implementation
LinkedListStack<String> lls = new LinkedListStack<>();
String s3 = "Tonight"; //this does not print but is removed from Stack
String s4 = "We Conqure"; //prints fine
String s5 = "Stacks"; //prints fine
lls.push(s5);
lls.push(s4);
lls.push(s3);
while (!lls.isEmpty()){
System.out.println(lls.pop()); //LINE 32
}
}
}
It appears you're popping the top off and then reading the new top's value in the pop() method
It should look like this:
public T pop (){
if (isEmpty()){
throw new RuntimeException("Stack is empty");
}
else{
T ret = top.data;
top = top.next;
return ret;
}
}
While you're at it, you might as well fix your peek()
public T peek(){
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return top.data;
}
Related
I have this piece of code where I am actually pushing element into the stack and I did make it but if I want to pop, peek and get the size of the stack afterwards how it should be actually done? Anyone who can provide help I can say thanks a lot for your time.
public class MyGenericsStack<T extends Object> {
private int stackSize;
private T[] stackArr;
private int top;
#SuppressWarnings("unchecked")
public MyGenericsStack(int size) {
this.stackSize = size;
this.stackArr = (T[]) new Object[stackSize];
this.top = -1;
}
public void push(T entry){
if(this.isStackFull()){
System.out.println(("Stack is full. It is increased now"));
this.increaseStackCapacity();
}
System.out.println("Add it: "+entry);
this.stackArr[++top] = entry;
}
public T pop() throws Exception {
if(this.isStackEmpty()){
throw new Exception("Stack is empty. You can't remove element.");
}
T entry = this.stackArr[top--];
System.out.println("Removed: "+entry);
return entry;
}
public T peek() {
return stackArr[top];
}
private void increaseStackCapacity(){
#SuppressWarnings("unchecked")
T[] newStack = (T[]) new Object[this.stackSize*2];
for(int i=0;i<stackSize;i++){
newStack[i] = this.stackArr[i];
}
this.stackArr = newStack;
this.stackSize = this.stackSize*2;
}
public boolean isStackEmpty() {
return (top == -1);
}
public boolean isStackFull() {
return (top == stackSize - 1);
}
public static void main(String a[]){
MyGenericsStack<String> Stack = new MyGenericsStack<String>(4);
Stack.push("kkk");
Stack.push("sss");
Stack.push("ppp");
Stack.push("aaa");
}
}
I'm not sure what you think is wrong with your pop abd peek methods, they look fine to me.
To get the size, you can write a method returning this.top + 1 - this.top holds the last index in the array that was filled, so adding 1 to it will give you the amount of elements stored in the internal array.
public int size() {
return this.top + 1;
}
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
I am trying to implement a shallow copy for a Linked Stack, but I am failing the J-unit test provided by my instructor.
I have tried to implement a for loop that will cycle through the stack top to bottom and create a reference for each node to the new list on the pass through. I've added a print statement and the data references seem to match up,but my test are still failing.
public class LinkedStack<E> implements Stack<E>{
private int size = 0;
// Unlike the book, we'll use an inner class for our Node.
// Its two data members can be accessed directly by the Stack
// code, so we don't need setters and getters.
protected class Node{
E data;
Node next;
}
protected Node top; // not public, but can still be seen by other classes in the
// csci211 package.
/** Create an empty stack.
*
*/
public LinkedStack(){
top = null;
}
#Override // see interface for comments.
public void push(E e){
//TODO 75
Node temp = new Node();
temp.data = e;
temp.next = top;
top = temp;
}
#Override // see interface for comments.
public E pop(){
if (top==null) {
throw new NoSuchElementException("Cannout pop an Empty Stack.");
}
E topvar;
topvar = top.data;
top = top.next;
return topvar;
}
#Override // see interface for comments.
public E peek() {
if (top == null) {
throw new NoSuchElementException("Cannout peek an Empty Stack.");
}
//E topvar;
//topvar = top.data;
return top.data;
}
/** Retrieve the number of elements on this stack.
*
* #return an int containing the number of elements
*/
public int size() {
return this.size;
}
/** An Iterator for our LinkedStack.
*
* #author rhodes
*
*/
class LinkedStackIterator implements Iterator<E> {
LinkedStack<E>.Node next; // the book calls this "current"
public LinkedStackIterator(LinkedStack<E> s){
next = s.top;
}
#Override
public boolean hasNext() {
return top != null;
//TODO 100
//return false;
}
#Override
public E next() {
if (!hasNext()) throw new NoSuchElementException();
E data = top.data;
top = top.next;
return data;
//TODO 100
//return null;
}
}
#Override
public void add(E element) {
push(element);
}
#Override
public void clear() {
this.top = null;
this.size = 0;
}
#Override
public List<E> shallowCopy() {
LinkedStack<E> newstack = new LinkedStack<E>();
ArrayList<E> Alist = new ArrayList<E>();
//Iterate through while we haven't hit the end of the stack
Node newtest = top;
while (newtest != null) {
Alist.add(newtest.data);
newtest = newtest.next;
//TODO 85
}
for(int i = Alist.size()-1;i>=0;i--) {
newstack.push(Alist.get(i));
}
return newstack;
}
#Override
public Iterator<E> iterator() {
return new LinkedStackIterator(this);
}
}
This is the Junit tests that I am failing
#Test
#SuppressWarnings("deprecation") // for Date.setHours(), Date.getHours()
public void shallowCopy1() {
// let's use Date, since it's mutable.
LinkedStack<Date> s = new LinkedStack<Date>();
Date d = new Date();
d.setHours(17);
s.push(d);
LinkedStack<Date> s2 =(LinkedStack<Date>) s.shallowCopy();
Date d2=s2.pop();
// The shallow copy should contain references to the same objects
// as the original.
assertTrue(d == d2);
// So, we can change the Date in the original list using the Date that
// came from the shallow copy.
d2.setHours(14);
assertTrue(d.getHours() == 14);
// I don't usually put two asserts in one test, but this seems like
// an instructive example.
}
#Test(expected=NoSuchElementException.class)
public void shallowCopy2() {
LinkedStack<Integer> s1 = new LinkedStack<Integer>();
for(int i=0; i<10; i++) {
s1.push(i);
}
LinkedStack<Integer> s2 =(LinkedStack<Integer>) s1.shallowCopy();
s2.push(10); // supposed to only affect s2
s2.push(11); // supposed to only affect s2
for(int i=0; i<10; i++) {
s1.pop();
}
int last = s1.pop(); // should throw
}
#Test
public void shallowCopy3() {
LinkedStack<Integer> q1 = new LinkedStack<Integer>();
for(int i=0; i<10; i++) {
q1.push(i);
}
LinkedStack<Integer> q2 =(LinkedStack<Integer>) q1.shallowCopy();
//Let's check that the order of elements is correct in the copy.
for(int i=0; i<10; i++) {
int v1=q1.pop();
int v2=q2.pop();
assertEquals(v1, v2);
}
}
If anyone could point me in the right direction I would appreciate it. This is a Homework Problem.
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.
protected class Node{
E data;
Node next;
Node(Node node){
this.next = node.next;
this.data = node.data;
}
}
#Override
public List<E> shallowCopy() {
// LinkedStack<E> newStack = new LinkedStack<E>();
//Iterate through while we haven't hit the end of the stack
Node s = new Node(top);
while (top.next != null) {
s.next = new Node(top.next);
top = top.next;
s = s.next;
}
System.out.println("FINSHED!");
return (List<E>) s;
}
#Override
public List<E> shallowCopyWithoutUpdatingNodeClass() {
// LinkedStack<E> newStack = new LinkedStack<E>();
//Iterate through while we haven't hit the end of the stack
Node s = new Node(top);
while (top.next != null) {
s.next = new Node();
s.next.next = top.next;
s.next.data = top.data;
top = top.next;
s = s.next;
}
System.out.println("FINSHED!");
return (List<E>) s;
}
Answer Inspired by :- What is the difference between a deep copy and a shallow copy?
The original problem was the node data was just being overwritten not creating a new node. Then the stack was backwards. Finally I implement and array to reverse the stack.
#Override
public List<E> shallowCopy() {
LinkedStack<E> newstack = new LinkedStack<E>();
ArrayList<E> Alist = new ArrayList<E>();
//Iterate through while we haven't hit the end of the stack
Node newtest = top;
while (newtest != null) {
Alist.add(newtest.data);
newtest = newtest.next;
//TODO 85
}
for(int i = Alist.size()-1;i>=0;i--) {
newstack.push(Alist.get(i));
}
//System.out.println("FINSHED!");
return newstack;
}
I'm trying to write code in a way that it is object oriented. In this particular case I want to keep track of the minimum value of my stack in O(1) time. I know how to do it, the idea of it, well my idea of it, which is to have another stack that keeps track of the minimum value for every push and pop.
I've nested every class inside of the program class which is called minStack, which doesn't seem like the right thing to do however when I create a instance of minStack and call its variables it works out fine for a regular stack. I created a class that extends a Stack called StackWithMin but I don't know how to call its values. Should I create a new instance of a StackWithMin? If so how would i do it? I did it at the end of the code above the main function, but peek() always returns null
class minStack {
public class Stack {
Node top;
Object min = null;
Object pop() {
if(top != null) {
Object item = top.getData();
top = top.getNext();
return item;
}
return null;
}
void push(Object item) {
if(min == null) {
min = item;
}
if((int)item < (int)min) {
min = item;
}
Node pushed = new Node(item, top);
top = pushed;
}
Object peek() {
if(top == null) {
//System.out.println("Its null or stack is empty");
return null;
}
return top.getData();
}
Object minimumValue() {
if(min == null) {
return null;
}
return (int)min;
}
}
public class Node {
Object data;
Node next;
public Node(Object data) {
this.data = data;
this.next = null;
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public void setNext(Node n) {
next = n;
}
public Node getNext() {
return next;
}
public void setData(Object d) {
data = d;
}
public Object getData() {
return data;
}
}
public class StackWithMin extends Stack {
Stack s2;
public StackWithMin() {
s2 = new Stack();
}
public void push(Object value) {
if((int)value <= (int)min()) {
s2.push(value);
}
super.push(value);
}
public Object pop() {
Object value = super.pop();
if((int)value == (int)min()) {
s2.pop();
}
return value;
}
public Object min() {
if(s2.top == null) {
return null;
}
else {
return s2.peek();
}
}
}
Stack testStack = new Stack();
StackWithMin stackMin = new StackWithMin();
public static void main(String[] args) {
minStack mStack = new minStack();
//StackWithMin stackMin = new StackWithMin();
mStack.testStack.push(3);
mStack.testStack.push(5);
mStack.testStack.push(2);
mStack.stackMin.push(2);
mStack.stackMin.push(4);
mStack.stackMin.push(1);
System.out.println(mStack.testStack.peek());
System.out.println(mStack.stackMin.peek());
mStack.testStack.pop();
}
}
I would suggest to create generic interface Stack like this one
interface Stack<T> {
void push(T item);
T pop();
T peek();
}
Generics add stability to your code by making more of your bugs
detectable at compile time.
See more about generics here.
Then implement this interface in a common way. All implementation details will be hidden inside of this class (your Node class for example). Here is the code (it is just to show the idea, if you want to use it you need to improve it with exception handling for example). Note that class Node is now also generic.
class SimpleStack<T> implements Stack<T> {
private class Node<T> { ... }
private Node<T> root = null;
public void push(T item) {
if (root == null) {
root = new Node<T>(item);
} else {
Node<T> node = new Node<T>(item, root);
root = node;
}
}
public T pop() {
if (root != null) {
T data = root.getData();
root = root.getNext();
return data;
} else {
return null;
}
}
public T peek() {
if (root != null) {
return root.getData();
} else {
return null;
}
}
}
Now we get to the part with stored minimum value. We can extend our SimpleStack class and add field with another SimpleStack. However I think this is better to make another implementation of the Stack and store two stacks for values and for minimums. The example is below. I have generalize the class that now uses Comparator to compare object, so you can use any other object types.
class StackWithComparator<T> implements Stack<T> {
private Comparator<T> comparator;
private SimpleStack<T> mins = new SimpleStack<>();
private SimpleStack<T> data = new SimpleStack<>();
public StackWithComparator(Comparator<T> comparator) {
this.comparator = comparator;
}
public void push(T item) {
data.push(item);
if (mins.peek() == null || comparator.compare(mins.peek(), item) >= 0) {
mins.push(item);
} else {
mins.push(mins.peek());
}
}
public T pop() {
mins.pop();
return data.pop();
}
public T peek() {
return data.peek();
}
public T min() {
return mins.peek();
}
}
Now you can use both implementations like so
SimpleStack<Integer> s1 = new SimpleStack<>();
s1.push(1);
s1.push(2);
s1.push(3);
System.out.println(s1.pop()); // print 3
System.out.println(s1.pop()); // print 2
System.out.println(s1.pop()); // print 1
StackWithComparator<Integer> s2 = new StackWithComparator<>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1, o2);
}
});
s2.push(1);
s2.push(2);
s2.push(3);
s2.push(0);
s2.push(4);
System.out.println(s2.min() + " " + s2.pop()); // print 0 4
System.out.println(s2.min() + " " + s2.pop()); // print 0 0
System.out.println(s2.min() + " " + s2.pop()); // print 1 3
System.out.println(s2.min() + " " + s2.pop()); // print 1 2
System.out.println(s2.min() + " " + s2.pop()); // print 1 1
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());
}
}