I’ve introduced the Stack structure in previous post. But considering the efficiency when we operating the entries, you may find that using an array(static one) is not good enough. So in this post, I’ll show you a whole new way to store elements——Linked Structure.
The advantage of linked structure is that it’s convenient to insert or delete element in any position. There won’t be a problem about moving elements. But its setback is also abvious, that is, you can’t randomly access an element unless it is head or back(if possible).
Implementation
First I’ll give a definition of a struct variable——Node, which is the basic element in storing data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
template <classNode_entry> structNode { // data members Node_entry entry; Node *next; // constructors Node() { next = NULL; } Node(Node_entry item, Node *add_on = NULL) { entry = item; next = add_on; } };
Then the definition of Stack is similar to the former one.
precondition: None. postcondition: Stack_entry item is added to the top of the Stack; returns Success or returns a code of OverFlow if dynamic memory is exhausted.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template <classStack_entry> Error_code LinkedStack<Stack_entry>::push(const Stack_entry &item) { if (top_node == NULL) { top_node = new Node<Stack_entry>(item); } else { Node<Stack_entry>* p = top_node; while (p->next != NULL) { p = p->next; } Node<Stack_entry>* temp = new Node<Stack_entry>(item); p->next = temp; } return Success; }
pop()
precondition: None. postcondition: The top of the Stack is removed. If the Stack is empty the method return UnderFlow; otherwise it returns Success.