DSA Assign3
DSA Assign3
DSA Assign3
int push(int x)
{
// creating new node
node *temp = new node;
temp->data = x;
temp->next = NULL;
if(front==NULL && rear == NULL)
{
front=rear = temp;
}
else
{
rear->next = temp;
rear=temp;
}
count++;
return 0;
}
int pop()
{
int p=0;
if(front == NULL)
return 0;
if(front == rear)
front=rear=NULL;
else
{
// iteratively removing element from front and
// storing in a new node at the back of linked list
for(int i=1;i<=count-1;i++)
{
node *temp = new node;
temp -> data = front->data;
temp-> next = NULL;
rear-> next = temp;
rear = temp;
front = front->next;
}
count--;
}
p = front->data;
front = front->next;
return p;
}
int main() {
Output:
2. Program to reverse a string using recursion.
rev.size = st.size;
rev.top = -1;
rev.s = new int[st.size];
Output:
3. Program to print the length of the valid longest
prefix.
struct stack
{
int top;
int size;
int *s;
};
int main()
{
struct stack st;
string expr;
int t;
Output:
struct stack
{
int top;
int size;
int *s;
};
int main()
{
string expr;
int k = 0;
cout << "Enter the expression = ";
cin >> expr;
struct stack st;
st.size = expr.length();
st.top = -1;
st.s = (int *)malloc(sizeof(int) * st.size);
if (st.top == -1)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
Output:
5. Program to print the number of days after which
no plant dies.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> vec(n);
for (int i = 0; i < n; i++)
{
cin >> vec[i];
vec[i] = -vec[i];
}
stack<element> st;
int ans = 0;
for (int i = 0; i < n; i++)
{
if (st.empty())
{
st.push({vec[i], 0});
}
else
{
element temp = st.top();
if (vec[i] < temp.ele1)
{
int cnt = 1;
ans = max(ans, cnt);
st.push({vec[i], cnt});
}
else
{
element know = st.top();
int present = know.ele2;
while (!st.empty() && know.ele1 <= vec[i])
{
st.pop();
if (st.empty())
{
break;
}
present = max(present, know.ele2);
know = st.top();
}
if (st.empty())
{
st.push({vec[i], 0});
}
else
{
st.push({vec[i], present + 1});
ans = max(ans, present + 1);
}
}
}
}
cout << ans << endl;
return 0;
}
Output:
6. Program to determine whether each sequence of
brackets is balanced.
// C++ program to check for balanced brackets.
#include <iostream>
using namespace std;
struct stack
{
int top;
int size;
int *s;
};
int main()
{
string expr;
struct stack st;
int t;
st.size = expr.length();
st.s = (int *)malloc(sizeof(int) * st.size);
st.top = -1;
for (int i = 0; i < expr.length(); i++)
{
if (st.top == -1)
{
// If the stack is empty
// just push the current bracket
st.top++;
st.s[st.top] = expr[i];
}
else if ((st.s[st.top] == '(' && expr[i] == ')') ||
(st.s[st.top] == '{' && expr[i] == '}') || (st.s[st.top] == '[' && expr[i]
== ']'))
{
Output:
struct stack
{
int top;
int size;
int *s;
};
int decr(struct stack *st, int sum)
{
int x = st->s[st->top];
sum = sum - x;
st->top--;
return sum;
}
int main()
{
struct stack st1, st2, st3;
int sum1 = 0, sum2 = 0, sum3 = 0;
int maxim;
int i = 0, x;
Output:
Thank You!!!