How to delete the middle element of a stack in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

public class Program
{
	private static void deleteMiddleElement(Stack<char> st, int size, int current = 0) {
		if (st.Count == 0 || current == size) {
			return;
		}

		char el = st.Peek();

		st.Pop();

		deleteMiddleElement(st, size, current + 1);

		if (current != size / 2) {
			st.Push(el);
		}
	}
	public static void Main(string[] args)
	{
		Stack<char> st = new Stack<char>();

		st.Push('3');
		st.Push('5');
		st.Push('1');
		st.Push('m');
		st.Push('9');
		st.Push('2');
		st.Push('7');

		deleteMiddleElement(st, st.Count);

		Console.WriteLine(string.Join(" ", st.ToArray()));
	}
}






/*
run:
 
7 2 9 1 5 3
 
*/

 



answered May 24, 2023 by avibootz
edited May 27, 2023 by avibootz
...