• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Stack program  RSS feed

 
Justin Liao
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am new to Java programming, thus I am not quite sure am I writing the code right
Please help me point out anything that is wrong.
Thanks.

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Stack<E>
{
private int N;
private Node first;


private class Node
{
private E e;
private Node next;

}
// The constructor initializes the stack to be empty.
public Stack()
{
first = null;
N = 0;
}


// push() takes an element of the appropriate type and pushes it on to
// the stack.
public void push(E e)
{
Node oldfirst = first;
first = new Node();
first.e = e;
first.next = oldfirst;
N++;
}


// pop() removes the element at the top of the stack. If the stack is
// empty, there are no elements to be removed, so a StackEmptyException
// is thrown instead.
public void pop()
throws StackEmptyException
{
if(isEmpty())
throw new StackEmptyException();
first = first.next;
N--;
}


// top() returns the element at the top of the stack without removing it.
// If the stack is empty, there is no element to be returned, so a
// StackEmptyException is thrown instead.
public E top()
throws StackEmptyException
{
if(isEmpty())
throw new StackEmptyException();
return first.e;
}


private Exception StackEmptyException(String string)
{
// TODO Auto-generated method stub
return null;
}


// isEmpty() returns true if the stack is empty and false if it's not.
public boolean isEmpty()
{
return first ==null;
}
}
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!