Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- struct Node
- {
- int val;
- Node * next;
- };
- struct LinkedList
- {
- private:
- Node * head = NULL;
- public:
- void push_front(int v)
- {
- Node node1;
- Node * temp = new Node;
- (*temp).val = v;/// temp -> val = v; temp -> n
- temp->next = NULL;
- if (head == NULL)
- {
- head = temp;
- }
- else
- {
- temp->next = head;
- head = temp;
- }
- }
- int get_front_element()
- {
- if (head == NULL)
- {
- printf("No element\n");
- return -1;
- }
- else
- return head->val;
- }
- void display()
- {
- if (head == NULL)
- printf("No element!\n");
- else
- {
- Node * temp = head;
- while (temp != NULL)
- {
- printf("%d ", temp->val);
- temp = temp->next;
- }
- printf("\n");
- }
- }
- void dispose()
- {
- Node * temp;
- while (head != NULL)
- {
- temp = head;
- head = head->next;
- delete temp;
- }
- printf("All elements are cleared!\n");
- }
- int pop_front()
- {
- if (head == NULL)
- {
- printf("Linked List is empty");
- return -1;
- }
- else
- {
- Node * temp = head;
- head = temp->next;
- int ret = temp->val;
- delete temp;
- return ret;
- }
- }
- };
- class Stack
- {
- LinkedList l1;
- int n = 0;
- public:
- void push(int v)
- {
- n++;
- l1.push_front(v);
- }
- int pop()
- {
- if (n == 0)
- {
- printf("Stack is empty");
- return -1;
- }
- n--;
- return l1.pop_front();
- }
- int size()
- {
- return n;
- }
- int peek()
- {
- return l1.get_front_element();
- }
- int isEmpty()
- {
- return !n;
- }
- void display()
- {
- l1.display();
- }
- void dispose()
- {
- l1.dispose();
- }
- };
- int main()
- {
- Stack s;
- s.push(1);
- s.push(2);
- s.push(3);
- s.push(4);
- s.push(5);
- printf("Stack Top: %d\n", s.peek());
- int x = s.pop();
- printf("Popped element is : %d\n", x);
- printf("Stack Top: %d\n", s.peek());
- s.dispose();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement