I. Chain Stacks
The stack with chain storage structure is called chain Stack, which is realized by single linked list. The first node of a single-linked list is the top node of the stack, and the top node of the stack is placed, and the stack operation is to insert a new node before the top node of the current stack, and the stack operation is to delete the top node of the current stack and return the top element value, and then point top to the new stack top node. The empty stack (a) of the chain stack (a), the stack operation (b), and the stack operation (c) are shown in the following illustration:
two. Chain Stack implementation 1. Define a chain stack
The previous article itself implements the collection framework (11): The Stack interface definition introduces the definition of the stack interface, the chain stack class Linkedstack implements the stack interface Sstack, and implements the method defined in the stack interface, as shown in the code:
Code Explanation:
The ① chain stack implements the Stack interface class Sstack, but cannot inherit the previously implemented single-linked list class singlylinkedlist because the stack does not support the insertion and deletion of linear tables anywhere. 2. Determine if the stack is empty
Code Explanation
The basis of whether the ① chain stack is empty is to determine if the top node of the stack is empty. 3. Into the stack
Code Explanation:
①top points to the top node of the stack, and the stack operation is to insert a new node before the top node of the current stack. 4. The Stack
Code Explanation:
① the stack operation is to delete the top node of the current stack and return the value of the top element of the stack, and then point top to the new stack top node. 5. Take the top element value of the stack
6. Overriding the ToString () method
three. Testing
The result of the operation is shown in the following figure:
Four. Time complexity analysis
Stack in the stack, the stack operations are at the top of the stack, do not need to traverse the single linked list, so the stack of the stack Operation push (), the stack Operation Pop () and take the top element get () The time complexity is O (1). Five. Source code example