Delete item from a stack

1

I have a whole type stack in the console of c # and I want to delete an element inside it, the element must be written by the user, for example: If I have the data in the stack: 12, 34, 54, 6, 44, a message will appear on the screen: "Enter the data you want to delete", if the user enters 44, the stack should be displayed without the data. I'm doing it with the Pop method but I have a problem, pop just deletes the first data, I want you to delete a specific data

THIS METHOD ONLY ERASES THE FIRST FACT:

 public void usePop()
        {

            showStackElements();
            Console.WriteLine("Ingrese el valor que desea eliminar");
            int valor = (int)stack.Pop();

            Console.WriteLine("Elemento " + valor + " eliminado");

        }

I have modified the code trying to save a variable (value) and I have entered that variable in the stack.Pop (value) method but it gives me an error.

CODE WITH ERROR:

 public void usePop()
        {

            showStackElements();
            Console.WriteLine("Ingrese el valor que desea eliminar");
            int valor = Convert.ToInt32(Console.ReadLine());
            stack.Pop(valor);

            Console.WriteLine("Elemento " + valor + " eliminado");

        }

Thank you.

    
asked by megas 07.11.2018 в 02:06
source

2 answers

0

By definition, in a stack you can only remove the element that is at the top. Batteries are structures that follow the LIFO principle (Last In First Out, last enter first out), in other words, with an object of the Stack class you will not achieve your goal. A structure that allows you to remove any item it contains is the list (List class), using the Remove method, for example:

    Console.WriteLine("Ingrese el valor que desea eliminar");
    int valor = Convert.ToInt32(Console.ReadLine());
    list.Remove(valor);
    Console.WriteLine("Elemento " + valor + " eliminado");
    
answered by 07.11.2018 в 02:43
0

The typical solution to this problem would be with a secondary battery, where I'll flip the data from the first stack until I find the value to be deleted, and then, returning all the elements to the original stack (taking into account the fact that the stack will return the last item entered first, so they will be in the same order in which they were originally).

Since it is very simple code, and the idea is that you learn, I will give you the solution in pseudo-code, which would be something like:

Pedir valor a eliminar;
repetir
  Sacar un elemento de la pila original;
  Si no es igual al elemento a Eliminar
    Poner el elemento en la pila secundaria
hasta que la pila original esté vacía o el elemento sea igual al elemento a eliminar
repetir
  Sacar un elemento de la pila secundaria
  Poner el elemento en la pila original
hasta que la pila secundaria esté vacía.

A greeting.

    
answered by 07.11.2018 в 03:10