Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdio.h>
- #include <string.h>
- using namespace std;
- struct Node{
- int val;
- Node *next;
- };
- class Stack{
- private:
- Node *head = NULL;
- int size = 0;
- public:
- Stack(){
- size = 0;
- }
- void push_back(int in){
- Node *t1, *t2;
- t1 = head;
- while(t1 -> next != NULL)
- t1 = t1 -> next;
- t2 = new Node;
- t2 -> val = in;
- t2->next = NULL;
- t1->next = t2;
- size++;
- }
- void push_front(int in){
- Node *t;
- t = new Node;
- t -> val = in;
- if(head == NULL){
- t -> next = NULL;
- head = t;
- }
- else{
- t -> next = head;
- head = t;
- }
- size++;
- }
- int pop_back(){
- int val;
- if(head == NULL){
- cout << "Stack is Empty\n";
- return -1;
- }
- else{
- Node *t1;
- t1 = head;
- if(head -> next == NULL){
- val = head -> val;
- delete head;
- return val;
- }
- else{
- Node *chk = t1 -> next;
- while(chk -> next != NULL){
- t1 = chk;
- chk = chk -> next;
- }
- val = t1 -> val;
- delete chk;
- t1 -> next = NULL;
- }
- }
- return val;
- }
- int pop_front(){
- int val;
- if (head == NULL){
- cout << "Stack is Empty\n";
- return -1;
- }
- else{
- Node *t1;
- t1 = head;
- if (head->next == NULL){
- val = head->val;
- delete head;
- return val;
- }
- else{
- head = head -> next;
- val = head -> val;
- delete t1;
- }
- }
- return val;
- }
- int top(){
- if(head == NULL) return -1;
- return head -> val;
- }
- void show(){
- Node *t;
- t = head;
- while(t != NULL){
- cout << t -> val << ' ';
- t = t -> next;
- }
- cout << endl;
- }
- int find(int in){
- Node *t;
- t = head;
- int index = 0;
- if(head == NULL) return -1;
- else{
- while(t != NULL){
- index++;
- if(t -> val == in) return index;
- t = t -> next;
- }
- }
- return -1;
- }
- void del(){
- Node *t;
- while(head -> next != NULL)
- {
- t = head;
- head = head -> next;
- delete t;
- }
- }
- int length(){
- return size;
- }
- };
- int main(){
- Stack s;
- cout << "1. Push Front.\n";
- cout << "2. Push Back.\n";
- cout << "3. Pop Front.\n";
- cout << "4. Pop Back.\n";
- cout << "5. Print.\n";
- cout << "6. Top.\n";
- cout << "7. Search.\n";
- cout << "8. Exit.\n";
- while(true){
- int input, iin, delv;
- cin >> input;
- if(input == 1){
- cin >> iin;
- s.push_front(iin);
- }
- else if (input == 2)
- {
- cin >> iin;
- s.push_back(iin);
- }
- else if (input == 3)
- {
- delv = s.pop_front();
- }
- else if (input == 4)
- {
- delv = s.pop_back();
- }
- else if (input == 5)
- {
- s.show();
- }
- else if (input == 6)
- {
- cout << s.top() << endl;
- }
- else if (input == 7)
- {
- cin >> iin;
- if(s.find(iin) != -1) cout << "Found at " << s.find(iin) << " position\n";
- else cout << "Not Found\n";
- }
- else if (input == 8)
- {
- break;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement