Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.EmptyStackException;
- public class LinkedStack<T> {
- Node head;
- int count;
- public void push(T item) {
- if (head == null) {
- // The stack is empty
- Node newNode = new Node(item, null);
- head = newNode;
- } else {
- // Stack is not empty, create a new node at the top of the stack
- // The new item's next link goes to the "old" head
- Node newNode = new Node(item, head);
- // Now we can re-assign the link to the new head
- head = newNode;
- }
- }
- public T pop() throws EmptyStackException {
- // TODO: Write code to add pop functionality
- if (head == null) {
- throw new EmptyStackException();
- }
- else{
- T result = head.getData();
- head = head.getNext();
- count--;
- return result;
- }
- }
- public T peek() {
- // TODO: Write code to add peek functionality
- if (head == null) {
- throw new EmptyStackException();
- }
- else {
- return head.data;
- }
- }
- public int length() {
- Node n = head;
- int length = 0;
- while (n != null) {
- length++;
- n = n.next;
- }
- return length;
- }
- @Override
- public String toString() {
- // TODO: Write code to add toString functionality
- return "";
- }
- // Nested class Node
- private class Node {
- T data;
- Node next; //pointer to the next node
- // Constructor for inner class Node
- Node(T data, Node next) {
- this.data = data;
- this.next = next;
- }
- // Setters & Getters for inner class Node
- public T getData() {
- return data;
- }
- public void setData(T data) {
- this.data = data;
- }
- public Node getNext() {
- return next;
- }
- public void setNext(Node next) {
- this.next = next;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement