Hi There!

I'm Dan Schlegel, an Associate Professor in the Computer Science Department at SUNY Oswego

LinkedStack and LinkedQueue

LinkedStack.java

public class LinkedStack {

    private static class Node {
        int data;
        Node next;

        public Node(int data){
            this.data = data;
        }

        public Node(int data, Node next){
            this.data = data;
            this.next = next;
        }
    }

    private Node top;
    private int count = 0;

    public int size(){
        return count;
    }

    public void push(int d){
        if (top == null)
            top = new Node(d);
        else 
            top = new Node(d, top);
        count++;
    }


    public int peek(){
        return top.data;
    }

    public int pop(){
        int temp = top.data;
        top = top.next;
        count--;
        return temp;
    }
    
    @Override
    public String toString(){
        String retVal = "Linked stack of size: " + count + '\n';

        for (Node temp = top; temp != null; temp = temp.next)
            retVal += temp.data + " ";

        return retVal;
    }

    
    // Testing our LS:
    public static void main(String[] args){
        LinkedStack ll = new LinkedStack();
        ll.push(10);
        ll.push(45);
        ll.push(23);
        System.out.println(ll);
        System.out.println(ll.peek());
        System.out.println(ll.pop());
        System.out.println(ll);
    }
}

LinkedQueue.java

public class LinkedQueue {

    private static class Node {
        int data;
        Node next;

        public Node(int data){
            this.data = data;
        }

        public Node(int data, Node next){
            this.data = data;
            this.next = next;
        }
    }

    private Node head, tail;
    private int count = 0;

    public int size(){
        return count;
    }

    public void enqueue(int d){
        if (head == null)
            tail = head = new Node(d);
        else
            tail = tail.next = new Node(d);
        count++;
    }

    public int peek(){
        return head.data;
    }

    public int dequeue(){
        int temp = head.data;
        head = head.next;
        count--;
        return temp;
    }
    
    @Override
    public String toString(){
        String retVal = "Linked queue of size: " + count + '\n';

        for (Node temp = head; temp != null; temp = temp.next)
            retVal += temp.data + " ";

        return retVal;
    }

    
    // Testing our LQ:
    public static void main(String[] args){
        LinkedQueue ll = new LinkedQueue();
        ll.enqueue(10);
        ll.enqueue(45);
        ll.enqueue(23);
        System.out.println(ll);
        System.out.println(ll.peek());
        System.out.println(ll.dequeue());
        System.out.println(ll);
        
    }
}