Data structure - java implementation of stack (Stack)

A stack is a table restricted to insert and delete operations only at the end of the table.

We call the end of the stack that allows insertion and deletion as the top of the stack, and the other end as the bottom of the stack. The stack without any data elements is called the empty stack.

The stack is also known as the Last In First Out (Last In First Out) structure, or LIFO structure for short, because of its feature that insertion and deletion can only be done at the end of the list.


The insertion operation of the stack is called push, also called push, push.

The delete operation of the stack is called Pop.

Since the stack is a special kind of table, we talked about the linear list and the linked list earlier. The advantage of the linear list is reading, while the advantage of the linked list is insertion and deletion.

For the stack, it is more about insertion and deletion operations, so we use a linked list structure to implement the stack.


push operation

The operation of pushing the stack is actually the insertion operation of the singly linked list, but the insertion position is at the end of the list.


See the complete code:

    public void push(Elem e) {
        Node node = new Node ();
        node.data = e;
        node.next = top;
        top = node;
        length++;
    }

The idea is very clear. After inserting the element to be pushed into the end of the list, change the point of the top pointer, and then increase the length by one.


pop operation

Similarly, the pop operation is actually the deletion of the singly linked list, but the deletion is at the end of the list.


Full code:

public Elem pop() {
    if (top == null) {
        LogUtil.d(TAG, "Stack is empty, can not pop");
        return null;
    }
    Node temp = top;
    top = top.next;

    length--;
    return temp.data;
}

Note that when deleting, you need to determine whether the stack is empty.


At this point, the stack operation comes to an end.

There are still many applications of stacks in software development, such as the back function of browsers, the undo function of editing software, binary conversion, and evaluation of four arithmetic expressions. In the following articles, some typical examples will be selected to describe the application of stacks.


At the end of the article, I recommend an app developed by myself, Google Play:  Data Structure and Algorithm Tutorial  (requires scientific Internet access)

Provides rich animation demonstrations and simulation scenarios to help you better understand abstract data structures and complex algorithms. (The animations in the text are all clips from the app)



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324693057&siteId=291194637