链表实现栈Java

链表实现栈-Java

package MyStack;

/**
 * 链表实现
 * @param <AnyType>
 */
public class MyStackLinked<AnyType> {
    
    
    private int theSize;
    private Node<AnyType> head;
    private Node<AnyType> tail;

    public MyStackLinked() {
    
    }

    private static class Node<AnyType> {
    
    
        private AnyType data;
        private Node<AnyType> next;

        public Node(AnyType x, Node<AnyType> n) {
    
    
            data = x;
            next = n;
        }
    }

    public int size() {
    
    
        return theSize;
    }

    public boolean isEmpty() {
    
    
        return theSize == 0;
    }

    public void push(AnyType data) {
    
    
        Node<AnyType> newNode = new Node<AnyType>(data, null);
        if (size() == 0) {
    
    
            head = newNode;
            tail = newNode;
            theSize++;
        } else {
    
    
            newNode.next = head;
            head = newNode;
            theSize++;
        }
    }

    public AnyType pop() {
    
    
        if (size() == 0) {
    
    
            throw new IndexOutOfBoundsException("empty");
        }
        AnyType item = head.data;
        head = head.next;
        theSize--;
        return item;
    }

    public AnyType top() {
    
    
        if (size() == 0) {
    
    
            throw new IndexOutOfBoundsException("empty");
        }
        return head.data;
    }
}

测试

package MyLinkedList;

public class MyLinkedListTest {
    
    
    public static void main(String[] args) {
    
    
        MyLinkedList<String> mll = new MyLinkedList<String>();
        mll.add("a");
        mll.add("b");
        mll.add("c");

        for (String s : mll) {
    
    
            System.out.println(s);
        }

        mll.set(2, "cc");

        String str = mll.get(2);
        System.out.println(str);

        System.out.println(mll.size());

        System.out.println(mll.isEmpty());

        mll.remove(1);

        for (String s : mll) {
    
    
            System.out.println(s);
        }

        System.out.println("clear");
        mll.clear();

        for (String s : mll) {
    
    
            System.out.println(s);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/E_chos/article/details/114701760
今日推荐