Several implementations of the stack

182 阅读3分钟

Today, I will simply implement several stacks.the content is very simple, I posted the code directly, if you have questions, you can leave a message and discuss with me.

StackArrayList

/**
 * This class implements a stack using an ArrayList
 * <p>
 * This is an ArratList implementation of a stack, where size is not
 * a problem we can extend the stack as much as we want.
 *
 */
public class StackArrayList {

    /**
     * ArrayList representation of the stack
     */
    private ArrayList<Integer> stackList;

    /**
     * Constructor
     */
    public StackArrayList() {
        this.stackList = new ArrayList<>();
    }

    /**
     * Adds value to the end of list which
     * is the top for the stack
     * @param value
     */
    public void push(int value) {
        stackList.add(value);
    }

    public int pop() {
        if (!isEmpty()) {
            int popVlue = stackList.get(stackList.size() - 1);
            stackList.remove(stackList.size() - 1);
            return popVlue;
        }
        System.out.println("The stack is already empty");
        return -1;
    }

    /**
     * Top element of the stack
     * @return
     */
    public int peek() {
        return stackList.get(stackList.size() - 1);
    }

    public boolean isEmpty() {
        return stackList.isEmpty();
    }

}

StackArray

/**
 * This class implements a Stack using a regular array.
 * <p>
 * A stack is exactly what is sounds like. An element gets added to the top of
 * the stack and only the element on the top may be removed. This is an example
 * of an array implementation of a Stack. So an element can only be added/removed
 * from the end of the array. In theory stack have no fixed size, but with an
 * array implementation it does
 */
public class StackArray {

    /**
     * The max size of the stack
     */
    private int maxSize;

    /**
     * The array representation of the Stack
     */
    private int[] stackArray;

    /**
     * The top of the Stack
     */
    private int top;

    /**
     * Constructor
     * @param maxSize size of the stack
     */
    public StackArray(int maxSize) {
        this.maxSize = maxSize;
        stackArray = new int[maxSize];
        top = -1;
    }

    /**
     * Adds an element to the top of the stack
     * @param value
     */
    public void push(int value) {
        if (!isFull()) {
            top++;
            stackArray[top] = value;
        } else {
            resize(maxSize * 2);
            push(value);
        }
    }

    /**
     * Remove the top element of the stack and returns the value you've removed
     * @return
     */
    public int pop() {
        if (!isEmpty()) {
            return stackArray[top--];
        }

        if (top < maxSize / 4) {
            resize(maxSize / 2);
            return pop();
        } else {
            System.out.println("The stack is already empty!");
            return -1;
        }
    }

    /**
     * Returns the element at the top of the stack
     * @return
     */
    public int peek() {
        if (!isEmpty()) {
            return stackArray[top];
        } else {
            System.out.println("The stack is empty, cant peek");
            return -1;
        }
    }

    /**
     * Rebuild a new size array
     * @param newSize
     */
    private void resize(int newSize) {
        int[] transferArray = new int[newSize];

        for (int i = 0; i < stackArray.length; i++) {
            transferArray[i] = stackArray[i];
        }
        stackArray = transferArray;
        maxSize = newSize;
    }

    public boolean isFull() {
        return (top + 1 == maxSize);
    }

    public boolean isEmpty() {
        return (top == -1);
    }


}

StackOfLinkedList

public class StackOfLinkedList {

    //A node class
    class Node {
        public int data;
        public Node next;

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

    /**
     * A class which implements a stack using a linked list
     * Contains all the stack methods : push pop printStack isEmpty
     */
    class LinkedListStack {

        Node head = null;

        public void push(int x) {
            Node n = new Node(x);
            if (head == null) {
                head = n;
            } else {
                Node temp = head;
                n.next = temp;
                head = n;
            }
        }

        public void pop() {
            if (head == null) {
                System.out.println("Empty stack, Nothing to pop");
            }
            Node temp = head;
            head = head.next;
            System.out.println("Poped element is : " + temp.data);
        }

        public int peek() {
            if (head == null) {
                return -1;
            }
            return head.data;
        }

        public void printStack() {
            Node temp  = head;
            System.out.println("Stack is printed as below: ");
            while (temp != null) {
                if (temp.next == null) {
                    System.out.println(temp.data);
                } else {
                    System.out.println(temp.data + " ->");
                }
                temp = temp.next;
            }
            System.out.println();
        }

        public int getSize() {
            if (head == null) {
                return 0;
            } else {
                int size = 1;
                Node temp = head;
                while (temp.next != null) {
                    temp = temp.next;
                    size++;
                }
                return size;
            }
        }
    }
}

NodeStack

/**
 * Implementation of a stack using nodes
 * @param <Item>
 */
public class NodeStack<Item> {

    /**
     * Information each node should contain
     * @value data : information of the value in the node
     * @value head : the head of the stack
     * @value next : the next value from this node
     * @value previous : the last value from this node
     * @value size : size of the stack
     */
    private Item data;
    private static NodeStack<?> head;
    private NodeStack<?> next;
    private NodeStack<?> previous;
    private static int size = 0;

    /**
     * Constructor for the NodeStack
     */
    public NodeStack() {
    }

    private NodeStack(Item item) {
        this.data = item;
    }

    /**
     * Put a value onto the stack
     * @param item
     */
    public void push(Item item) {

        NodeStack<Item> newNs = new NodeStack<Item>(item);

       if (this.isEmpty()) {
           NodeStack.setHead(new NodeStack<>(item));
           newNs.setNext(null);
           newNs.setPrevious(null);
       } else {
           newNs.setPrevious(NodeStack.head);
           NodeStack.head.setNext(newNs);
           NodeStack.head = newNs;
       }

       NodeStack.setSize(NodeStack.getSize() + 1);
    }

    /**
     * Value to be taken off the stack
     * @return value that is returned
     */
    public Item pop() {
        Item item = (Item) NodeStack.head.getData();

        NodeStack.head  = NodeStack.head.getPrevious();
        NodeStack.head.setNext(null);

        NodeStack.setSize(NodeStack.getSize() - 1);

        return item;
    }

    /**
     * Value that is next to be taken off the stack
     * @return
     */
    public Item peek() {
        return (Item) NodeStack.head.getData();
    }

    public boolean isEmpty() {
        return NodeStack.getSize() == 0;
    }

    public Item getData() {
        return data;
    }

    public void setData(Item data) {
        this.data = data;
    }

    public static NodeStack<?> getHead() {
        return head;
    }

    public static void setHead(NodeStack<?> head) {
        NodeStack.head = head;
    }

    public NodeStack<?> getNext() {
        return next;
    }

    public void setNext(NodeStack<?> next) {
        this.next = next;
    }

    public NodeStack<?> getPrevious() {
        return previous;
    }

    public void setPrevious(NodeStack<?> previous) {
        this.previous = previous;
    }

    public static int getSize() {
        return size;
    }

    public static void setSize(int size) {
        NodeStack.size = size;
    }
}

BalanceBrakets

public class BalanceBrackets {

    static boolean is_balanced(String s) {
        Stack<Character> bracketsStack = new Stack<>();
        char[] text = s.toCharArray();
        for (char x : text) {
            switch (x) {
                case '{':
                case '<':
                case '(':
                case '[':
                    bracketsStack.push(x);
                    break;
                case '}':
                    if (bracketsStack.peek() == '{') {
                        bracketsStack.pop();
                        break;
                    } else {
                        return false;
                    }
                case '>':
                    if (bracketsStack.peek() == '<') {
                        bracketsStack.pop();
                        break;
                    } else {
                        return false;
                    }
                case ')':
                    if (bracketsStack.peek() == '(') {
                        bracketsStack.pop();
                        break;
                    } else {
                        return false;
                    }
                case ']':
                    if (bracketsStack.peek() == '[') {
                        bracketsStack.pop();
                        break;
                    } else {
                        return false;
                    }
            }
        }
        return bracketsStack.empty();
    }
}

An algorithmic problem

leetcode-cn.com/problems/ad…

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.

public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
    val = x;
    }
}
public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode dummyHead = new ListNode(0);
            ListNode p = l1;
            ListNode q = l2;
            ListNode curr = dummyHead;
            int carry = 0;
            while (p != null || q != null) {
                int x = (p != null) ? p.val : 0;
                int y = (q != null) ? q.val : 0;
                int digit = carry + x + y;
                carry = digit / 10;
                curr.next = new ListNode(digit % 10);
                curr = curr.next;
                if (p != null) {
                    p = p.next;
                }
                if (q != null) {
                    q = q.next;
                }
            }
            if (carry > 0) {
                curr.next = new ListNode(carry);
            }
            return dummyHead.next;
        }
    }

}

End,thanks for reading!