Stacks:
Stacks are very similar to singly-linked lists in implementation. Here are the very basic code and its explanation to implement stacks using classes in c++.
First, we will create a class for nodes, its objects will represent each node in our stack.
class Node{ private: int data; Node* next; public: int getData(){ return data; } Node* getNext(){ return next; } void setData(int a){ data = a; } void setNext(Node* n){ next = n; } };
The code is very easy, creates a class with private fields containing data and a pointer to contain the address of the node beneath any object in the stack.
Now the Stacks class:
class Stacks{ private: Node* head; public: Stacks(){ head = NULL; } void push(int a){ Node* new_node = new Node; new_node->setData(a); new_node->setNext(head); head = new_node; } int top(){ if(head!=NULL) return head->getData(); return -1; } int pop(){ if(head!=NULL){ int temp = head->getData(); head = head->getNext(); return temp; } return -1; } bool isempty(){ return head == NULL; } };
The private field of the class contains a pointer to the head of our stack. In the public field, we have a push function, which pushes the data to the head of the stack. The idea is simple first create a new node, assign it the pointer to the next node, which is stored in the head, now assign head the address of this new node.
Then there is a top function, which simply returns the data in the node at the top.
The pop() function deletes the node at the head of the node and makes the head point to the next node. It also returns the data at this node.
isempty() checks if the stack is empty if it is, it returns true, else it returns false.
No comments:
Post a Comment