Saturday, August 30, 2025

STACK ADT

 #include <iostream>

 using namespace std;
 #define MAX 100
 class stack{
private:
int arr[MAX];
int top;
public:
stack(){
    top=-1;
}
void push(int value){
    if(top>=MAX-1){
        cout<<"Stack overflow "<<endl;
        return;
    }
    arr[++top]=value;
    cout<<value<<" has been added to stack \n";
}
void pop(){
    if (top < 0) {
            cout << "Stack Underflow! Nothing to pop." << endl;
            return;
        }
        cout << arr[top--] << " popped from stack." << endl;
    }
void peek(){
    if(top<0){
        cout<<"list is empty "<<endl;
        return;
    }
    cout<<"top element is "<<arr[top]<<endl;
}
void peek(int position){
int index=top-position+1;
if(index<0||index>top){
cout<<"invalid index"<<endl;
return;
}
cout<<"element at position"<<position<<"is"<<arr[index]<<endl;
}
int stackTop(stack &st){
if(top==-1){
cout<<"stack is empty"<<endl;
return -1
}
return st.arr[st.top];
}
int stackBottom(stack &st){
if(top==-1){
cout<<"stack is empty "<<endl;
return -1;
}
return st.arr[0];
}

void display(){
    if(top<0){
        cout<<"list is empty "<<endl;
    }
    for(int i=0;i<=top;i++){
        cout<<arr[i]<<endl;
    }
}
 };
 int main() {
 stack s;
 int choice,value;
 do{
       cout << "\n--- Stack Menu ---\n";
        cout << "1. Push\n";
        cout << "2. Pop\n";
        cout << "3. Peek\n";
        cout << "4. Display\n";
        cout << "5. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;
switch(choice){
     case 1:
            cout << "Enter value to push: ";
            cin >> value;
            s.push(value);
            break;
        case 2:
            s.pop();
            break;
        case 3:
            s.peek();
            break;
        case 4:
            s.display();
            break;
        case 5:
            cout << "Exiting program..." << endl;
            break;
        default:
            cout << " Invalid choice! Try again." << endl;
        }
    } while (choice != 5);
   
 return 0;
 }

No comments:

Post a Comment

list in c#

  using System ; using System . Collections . Generic ; class Program {     static void Main () {         // Write your C# code here  ...