Delete the middle element of the stack
IP: [1,2,3,4,5]
OP: [1,2,4,5]
Method1: First we remove all the elements, then push all elements except the middle element. Then pop all elements to print the element.
Code:
void deletemid(stack <char> &st, int n, int curr=0)
{ //do nothing if stack is empty or all items are traversed
//curr is currrent item number
if(st.empty() || curr==n) return;
//remove the currrent item
int x= st.top(); st.pop();
//remove other items;
deletemid(st, n. curr+1);
//put all elements back to stack except middle element
if(curr!=n/2) st.push(x);
} //f ends
int main()
{ stack<char> st;
st.push('1');
st.push('2'); st.push('3'); st.push('4');
st.push('5'); st.push('6'); st.push('7');
deletemid(st, st.size());
//printing the stack after deletion of middle element
while(!st.empty)
{ char p=st.top(); st.pop();
cout<<p<<"";
} return 0;
1 Comments:
Thanks for sharing the info, keep up the good work going.... I really enjoyed exploring your site. good resource...
swapza
Post a Comment
Subscribe to Post Comments [Atom]
<< Home