Answer to Question #295067 in C++ for Roe

Question #295067

Write a program that deletes duplicate elements from a stack.







Requirements:





No global decelerations





Test run the code in main

1
Expert's answer
2022-02-08T02:16:26-0500


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


// Function to remove adjacent
// duplicate elements
string ShortenString(string str1)
{
	
	// Store the string without
	// duplicate elements
	stack<char> st;
	
	// Store the index of str
	int i = 0;
	
	// Traverse the string str
	while (i < str1.length())
	{
		
		// Checks if stack is empty or top of the
		// stack is not equal to current character
		if (st.empty() || str1[i] != st.top())
		{
			st.push(str1[i]);
			i++;
		}
			
		// If top element of the stack is
		// equal to the current character
		else
		{
			st.pop();
			i++;
		}
	}
	
	// If stack is empty
	if (st.empty())
	{
		return ("Empty String");
	}
		
	// If stack is not Empty
	else
	{
		string short_string = "";
		while (!st.empty())
		{
			short_string = st.top() +
						short_string;
			st.pop();
		}
		return (short_string);
	}
}


// Driver Code
int main()
{
	string str1 ="smaaartzz";
	
	cout << ShortenString(str1);


	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog