OneCompiler

Stack DSA

1644

#include<bits/stdc++.h>
using namespace std;

struct Node{
char data;
Node* link;
};

class Stack{
Node* top;
public:
Stack(){
top = NULL;
}

void create();
void push(char ch);
void insertafter();
void insertbefore();
void display();

};

void Stack :: create(){
int n;
cin>>n;

for(int i = 0 ; i < n ; i++){
cin>>data;
push(data);
}
}

void Stack :: push(char ch){
Node* nn = new Node;
nn->data = ch;

nn->link = top;
top = nn;
}

void Stack :: insertafter(char target , char ch){
Node* temp = top;
while(temp!=NULL && temp->data!=target){
temp=temp->link;
}
while(temp == NULL){
cout<<"Not Found"<<endl;
return;
}

Node* nn = new Node;
nn->data = ch;

nn->link = temp->link;
temp->link = nn;
}

void Stack :: insertbefore(char target,char ch){
Node* temp = top;
Node* prev = nullptr;

while(temp!=NULL && temp->data!= target){
prev= temp;
temp=temp->data;
}
while(temp == NULL){
cout<<"Not found"<<endl;
return;
}

Node* nn = new Node;
nn->data = ch;
nn->link = temp;

if(prev == NULL){
top = nn;
}
else{
prev->link = nn;
}
}