Skip to main content

Remove all particular element from a stack

The problem of "Remove All Particular Element from a Stack" involves removing all occurrences of a specific element from a given stack while maintaining the order of the remaining elements. The task is to implement a function that takes a stack and a specific element as input and removes all occurrences of that element from the stack.

Problem Statement

Given a stack and a specific element, implement a function deleteNodes(int element) that removes all occurrences of the given element from the stack. The original stack should be modified in-place, and the order of the remaining elements should be preserved.

Example

Consider the following stack:

-3 <- Top
7
4
-3
9
-3
5
3
5

After deleting all occurrences of the element -3 from the stack, the result should be:

7 <- Top
4
9
5
3
5

Idea to Solve the Problem

To remove all occurrences of the given element from the stack, we can use an auxiliary stack. We will perform the following steps:

  1. Create an auxiliary stack to hold the elements that are not equal to the given element.
  2. While the original stack is not empty, do the following: a. Get the top element data of the original stack. b. Pop the top element from the original stack. c. If data is not equal to the given element, push data into the auxiliary stack.
  3. Add the elements from the auxiliary stack back into the original stack. This step will preserve the order of the remaining elements.

Pseudocode

Function deleteNodes(element):
    Create an auxiliary stack auxiliary
    While the original stack is not empty:
        Get the top element data from the original stack
        Pop the top element from the original stack
        If data is not equal to the given element:
            Push data into the auxiliary stack
    While the auxiliary stack is not empty:
        Get the top element data from the auxiliary stack
        Pop the top element from the auxiliary stack
        Push data into the original stack

Code Solution

// C program 
// Remove all particular element from a stack
#include <stdio.h>
#include <stdlib.h>

// Define stack node
struct StackNode
{
    int element;
    struct StackNode *next;
};
// Define a custom stack
struct MyStack
{
    struct StackNode *top;
    int size;
};
struct MyStack *newStack()
{
    //Make a stack
    struct MyStack *stack = (struct MyStack *) malloc(sizeof(struct MyStack));
    if (stack != NULL)
    {
        //Set node values
        stack->top = NULL;
        stack->size = 0;
    }
    else
    {
        printf("\nMemory overflow when create new stack\n");
    }
}
//Create a new node of stack
struct StackNode *newNode(int element, struct StackNode *next)
{
    //Make a new node
    struct StackNode *node = (struct StackNode *) malloc(sizeof(struct StackNode));
    if (node == NULL)
    {
        printf("\nMemory overflow when create new stack Node \n");
    }
    else
    {
        node->element = element;
        node->next = next;
    }
    return node;
}
// Returns the status of empty or non empty stacks
int isEmpty(struct MyStack *stack)
{
    if (stack->size > 0 && stack->top != NULL)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}
// Add node at the top of stack
void push(struct MyStack *stack, int element)
{
    // Add stack element
    stack->top = newNode(element, stack->top);
    stack->size++;
}
// return top element of stack
int peek(struct MyStack *stack)
{
    return stack->top->element;
}
// Remove top element of stack
void pop(struct MyStack *stack)
{
    if (isEmpty(stack) == 0)
    {
        struct StackNode *temp = stack->top;
        // Change top element of stack
        stack->top = temp->next;
        // remove previous top
        free(temp);
        temp = NULL;
        stack->size--;
    }
}

// Remove specific element from stack
void deleteNodes(struct MyStack *stack, int element)
{
  
    // Create auxiliary stack
    struct MyStack *auxiliary = newStack();
    int data = 0;
    // Executing the loop until when actual stack element are not empty
    while (isEmpty(stack) == 0)
    {
        // Get the top element of actual stack
        data = peek(stack);
        // Remove top of current actual stack
        pop(stack);

        if(data != element)
        {
           // Add data to auxiliary stack
            push(auxiliary, data);
        }
    }
    // Add remaining elements into actual stack
    while(isEmpty(auxiliary)== 0)
    {
        // Add node
        push(stack,peek(auxiliary));
        
        // Remove node in auxiliary stack
        pop(auxiliary);
    }
}

// Print element of stack
void printData(struct MyStack *stack)
{
    struct StackNode *temp = stack->top;
    // iterate stack elements
    while (temp != NULL)
    {
        // Display element value
        printf("  %d", temp->element);
        temp = temp->next;
    }
    printf("\n");
}
int main()
{
    struct MyStack *stack = newStack();
    // Add the stack element
    push(stack, 5);
    push(stack, 3);
    push(stack, 5);
    push(stack, -3);
    push(stack, 9);
    push(stack, -3);
    push(stack, 4);
    push(stack, 7);
    push(stack, -3);
    /*
    Created Stack
    ============

       -3 <- Top
        7
        4
       -3
        9
       -3
        5
        3
        5
    */
    printf("\n  Stack element \n");
    printData(stack);

    int element = -3;

    // delete operation
    deleteNodes(stack, element);
    /*
    After delete element -3 
    ============

        7 <- Top
        4
        9
        5
        3
        5
    */
    printf("\n  After delete element %d in stack \n",element);
    printData(stack);
   
    return 0;
}

Output

  Stack element
  -3  7  4  -3  9  -3  5  3  5

  After delete element -3 in stack
  7  4  9  5  3  5
/*
   Java Program
   Remove all particular element from a stack
*/
// Define stack node
class StackNode
{
    public int element;
    public StackNode next;
    public StackNode(int element, StackNode top)
    {
        this.element = element;
        this.next = top;
    }
}
// Define a custom stack
class MyStack
{
    public StackNode top;
    public int size;
    public MyStack()
    {
        //Set node values
        this.top = null;
        this.size = 0;
    }
    // Add node at the top of stack
    public void push(int element)
    {
        this.top = new StackNode(element, this.top);
        this.size++;
    }
    public boolean isEmpty()
    {
        if (this.size > 0 && this.top != null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    public void pop()
    {
        if (this.size > 0 && this.top != null)
        {
            StackNode temp = this.top;
            // Change top element of stack
            this.top = temp.next;
            // remove previous top
            temp = null;
            this.size--;
        }
    }
    // return top element of stack
    public int peek()
    {
        return this.top.element;
    }
}
public class DeleteOperation
{
    public MyStack stack;
    public DeleteOperation()
    {
        this.stack = new MyStack();
    }
    // Print element of stack
    public void printData()
    {
        StackNode temp = this.stack.top;
        while (temp != null)
        {
            // Display element value
            System.out.print("   " + temp.element);
            temp = temp.next;
        }
        System.out.print("\n");
    }
    // Remove specific element from stack
    public void deleteNodes(int element)
    {
        // Create auxiliary stack
        MyStack auxiliary = new MyStack();
        int data = 0;
        // Executing the loop until when actual stack element are not empty
        while (this.stack.isEmpty() == false)
        {
            // Get the top element of actual stack
            data = this.stack.peek();
            // Remove top of current actual stack
            this.stack.pop();
            if (data != element)
            {
              	// When data is not equal to given deleted element
                // Add data to auxiliary stack
                auxiliary.push(data);
            }
        }
        // Add remaining elements into actual stack
        while (auxiliary.isEmpty() == false)
        {
            // Add node
            this.stack.push(auxiliary.peek());
            // Remove node in auxiliary stack
            auxiliary.pop();
        }
    }
    public static void main(String[] args)
    {
        DeleteOperation task = new DeleteOperation();
        // Add the stack element
        task.stack.push(5);
        task.stack.push(3);
        task.stack.push(5);
        task.stack.push(-3);
        task.stack.push(9);
        task.stack.push(-3);
        task.stack.push(4);
        task.stack.push(7);
        task.stack.push(-3);
        /*
        Created Stack
        ============

           -3 <- Top
            7
            4
           -3
            9
           -3
            5
            3
            5
        */
        System.out.print("\n Stack element \n");
        task.printData();
        int element = -3;
        // delete operation
        task.deleteNodes(element);
        /*
        After delete element -3 
        ============

            7 <- Top
            4
            9
            5
            3
            5
        */
        System.out.print("\n  After delete element " + element + " in stack \n");
        task.printData();
    }
}

Output

 Stack element
   -3   7   4   -3   9   -3   5   3   5

  After delete element -3 in stack
   7   4   9   5   3   5
// Include header file
#include <iostream>
using namespace std;

/*
   C++ Program
   Remove all particular element from a stack
*/

// Define stack node
class StackNode
{
	public: int element;
	StackNode *next;
	StackNode(int element, StackNode *top)
	{
		this->element = element;
		this->next = top;
	}
};
// Define a custom stack
class MyStack
{
	public: 
    StackNode *top;
	int size;
	MyStack()
	{
		//Set node values
		this->top = NULL;
		this->size = 0;
	}
	// Add node at the top of stack
	void push(int element)
	{
		this->top = new StackNode(element, this->top);
		this->size++;
	}
	bool isEmpty()
	{
		if (this->size > 0 && this->top != NULL)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	// Remove top element of stack
	void pop()
	{
		if (this->size > 0 && this->top != NULL)
		{
			StackNode *temp = this->top;
			// Change top element of stack
			this->top = temp->next;
			// remove previous top
                        delete temp;
			temp = NULL;
			this->size--;
		}
	}
	// return top element of stack
	int peek()
	{
		return this->top->element;
	}
};
class DeleteOperation
{
	public: 
    MyStack stack;
	DeleteOperation()
	{
		this->stack =  MyStack();
	}
	// Print element of stack
	void printData()
	{
		StackNode *temp = this->stack.top;
		while (temp != NULL)
		{
			// Display element value
			cout << "   " << temp->element;
			temp = temp->next;
		}
		cout << "\n";
	}
	// Remove specific element from stack
	void deleteNodes(int element)
	{
		// Create auxiliary stack
		MyStack auxiliary = MyStack();
		int data = 0;
		// Executing the loop until when actual stack element are not empty
		while (this->stack.isEmpty() == false)
		{
			// Get the top element of actual stack
			data = this->stack.peek();
			// Remove top of current actual stack
			this->stack.pop();
			if (data != element)
			{
				// When data is not equal to given deleted element
				// Add data to auxiliary stack
				auxiliary.push(data);
			}
		}
		// Add remaining elements into actual stack
		while (auxiliary.isEmpty() == false)
		{
			// Add node
			this->stack.push(auxiliary.peek());
			// Remove node in auxiliary stack
			auxiliary.pop();
		}
	}
};
int main()
{
	DeleteOperation task = DeleteOperation();
	// Add the stack element
	task.stack.push(5);
	task.stack.push(3);
	task.stack.push(5);
	task.stack.push(-3);
	task.stack.push(9);
	task.stack.push(-3);
	task.stack.push(4);
	task.stack.push(7);
	task.stack.push(-3);
	/*
	        Created Stack
	        ============

	           -3 <- Top
	            7
	            4
	           -3
	            9
	           -3
	            5
	            3
	            5
	        */
	cout << "\n Stack element \n";
	task.printData();
	int element = -3;
	// delete operation
	task.deleteNodes(element);
	/*
	        After delete element -3 
	        ============

	            7 <- Top
	            4
	            9
	            5
	            3
	            5
	        */
	cout << "\n  After delete element " << element << " in stack \n";
	task.printData();
	return 0;
}

Output

 Stack element
   -3   7   4   -3   9   -3   5   3   5

  After delete element -3 in stack
   7   4   9   5   3   5
// Include namespace system
using System;
/*
   C# Program
   Remove all particular element from a stack
*/
// Define stack node
public class StackNode
{
    public int element;
    public StackNode next;
    public StackNode(int element, StackNode top)
    {
        this.element = element;
        this.next = top;
    }
}
// Define a custom stack
public class MyStack
{
    public StackNode top;
    public int size;
    public MyStack()
    {
        //Set node values
        this.top = null;
        this.size = 0;
    }
    // Add node at the top of stack
    public void push(int element)
    {
        this.top = new StackNode(element, this.top);
        this.size++;
    }
    public Boolean isEmpty()
    {
        if (this.size > 0 && this.top != null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    public void pop()
    {
        if (this.size > 0 && this.top != null)
        {
            StackNode temp = this.top;
            // Change top element of stack
            this.top = temp.next;
            // remove previous top
            temp = null;
            this.size--;
        }
    }
    // return top element of stack
    public int peek()
    {
        return this.top.element;
    }
}
public class DeleteOperation
{
    public MyStack stack;
    public DeleteOperation()
    {
        this.stack = new MyStack();
    }
    // Print element of stack
    public void printData()
    {
        StackNode temp = this.stack.top;
        while (temp != null)
        {
            // Display element value
            Console.Write("   " + temp.element);
            temp = temp.next;
        }
        Console.Write("\n");
    }
    // Remove specific element from stack
    public void deleteNodes(int element)
    {
        // Create auxiliary stack
        MyStack auxiliary = new MyStack();
        int data = 0;
        // Executing the loop until when actual stack element are not empty
        while (this.stack.isEmpty() == false)
        {
            // Get the top element of actual stack
            data = this.stack.peek();
            // Remove top of current actual stack
            this.stack.pop();
            if (data != element)
            {
                // When data is not equal to given deleted element
                // Add data to auxiliary stack
                auxiliary.push(data);
            }
        }
        // Add remaining elements into actual stack
        while (auxiliary.isEmpty() == false)
        {
            // Add node
            this.stack.push(auxiliary.peek());
            // Remove node in auxiliary stack
            auxiliary.pop();
        }
    }
    public static void Main(String[] args)
    {
        DeleteOperation task = new DeleteOperation();
        // Add the stack element
        task.stack.push(5);
        task.stack.push(3);
        task.stack.push(5);
        task.stack.push(-3);
        task.stack.push(9);
        task.stack.push(-3);
        task.stack.push(4);
        task.stack.push(7);
        task.stack.push(-3);
        /*
        Created Stack
        ============

           -3 <- Top
            7
            4
           -3
            9
           -3
            5
            3
            5
        */
        Console.Write("\n Stack element \n");
        task.printData();
        int element = -3;
        // delete operation
        task.deleteNodes(element);
        /*
        After delete element -3 
        ============

            7 <- Top
            4
            9
            5
            3
            5
        */
        Console.Write("\n  After delete element " + element + " in stack \n");
        task.printData();
    }
}

Output

 Stack element
   -3   7   4   -3   9   -3   5   3   5

  After delete element -3 in stack
   7   4   9   5   3   5
<?php
/*
   Php Program
   Remove all particular element from a stack
*/
// Define stack node
class StackNode
{
    public $element;
    public $next;

    function __construct($element, $top)
    {
        $this->element = $element;
        $this->next = $top;
    }
}
// Define a custom stack
class MyStack
{
    public $top;
    public $size;

    function __construct()
    {
        //Set node values
        $this->top = null;
        $this->size = 0;
    }
    // Add node at the top of stack
    public  function push($element)
    {
        $this->top = new StackNode($element, $this->top);
        $this->size++;
    }
    public  function isEmpty()
    {
        if ($this->size > 0 && $this->top != null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    public  function pop()
    {
        if ($this->size > 0 && $this->top != null)
        {
            $temp = $this->top;
            // Change top element of stack
            $this->top = $temp->next;
            // remove previous top
            $temp = null;
            $this->size--;
        }
    }
    // return top element of stack
    public  function peek()
    {
        return $this->top->element;
    }
}
class DeleteOperation
{
    public $stack;

    function __construct()
    {
        $this->stack = new MyStack();
    }
    // Print element of stack
    public  function printData()
    {
        $temp = $this->stack->top;
        while ($temp != null)
        {
            // Display element value
            echo "   ". $temp->element;
            $temp = $temp->next;
        }
        echo "\n";
    }
    // Remove specific element from stack
    public  function deleteNodes($element)
    {
        // Create auxiliary stack
        $auxiliary = new MyStack();
        $data = 0;
        // Executing the loop until when actual stack element are not empty
        while ($this->stack->isEmpty() == false)
        {
            // Get the top element of actual stack
            $data = $this->stack->peek();
            // Remove top of current actual stack
            $this->stack->pop();
            if ($data != $element)
            {
                // When data is not equal to given deleted element
                // Add data to auxiliary stack
                $auxiliary->push($data);
            }
        }
        // Add remaining elements into actual stack
        while ($auxiliary->isEmpty() == false)
        {
            // Add node
            $this->stack->push($auxiliary->peek());
            // Remove node in auxiliary stack
            $auxiliary->pop();
        }
    }
}

function main()
{
    $task = new DeleteOperation();
    // Add the stack element
    $task->stack->push(5);
    $task->stack->push(3);
    $task->stack->push(5);
    $task->stack->push(-3);
    $task->stack->push(9);
    $task->stack->push(-3);
    $task->stack->push(4);
    $task->stack->push(7);
    $task->stack->push(-3);
    /*
    Created Stack
    ============

       -3 <- Top
        7
        4
       -3
        9
       -3
        5
        3
        5
    */
    echo "\n Stack element \n";
    $task->printData();
    $element = -3;
    // delete operation
    $task->deleteNodes($element);
    /*
    After delete element -3 
    ============

        7 <- Top
        4
        9
        5
        3
        5
    */
    echo "\n  After delete element ". $element ." in stack \n";
    $task->printData();
}
main();

Output

 Stack element
   -3   7   4   -3   9   -3   5   3   5

  After delete element -3 in stack
   7   4   9   5   3   5
/*
   Node Js Program
   Remove all particular element from a stack
*/
// Define stack node
class StackNode
{
    constructor(element, top)
    {
        this.element = element;
        this.next = top;
    }
}
// Define a custom stack
class MyStack
{
    constructor()
    {
        //Set node values
        this.top = null;
        this.size = 0;
    }
    // Add node at the top of stack
    push(element)
    {
        this.top = new StackNode(element, this.top);
        this.size++;
    }
    isEmpty()
    {
        if (this.size > 0 && this.top != null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    pop()
    {
        if (this.size > 0 && this.top != null)
        {
            var temp = this.top;
            // Change top element of stack
            this.top = temp.next;
            // remove previous top
            temp = null;
            this.size--;
        }
    }
    // return top element of stack
    peek()
    {
        return this.top.element;
    }
}
class DeleteOperation
{
    constructor()
    {
        this.stack = new MyStack();
    }
    // Print element of stack
    printData()
    {
        var temp = this.stack.top;
        while (temp != null)
        {
            // Display element value
            process.stdout.write("   " + temp.element);
            temp = temp.next;
        }
        process.stdout.write("\n");
    }
    // Remove specific element from stack
    deleteNodes(element)
    {
        // Create auxiliary stack
        var auxiliary = new MyStack();
        var data = 0;
        // Executing the loop until when actual stack element are not empty
        while (this.stack.isEmpty() == false)
        {
            // Get the top element of actual stack
            data = this.stack.peek();
            // Remove top of current actual stack
            this.stack.pop();
            if (data != element)
            {
                // When data is not equal to given deleted element
                // Add data to auxiliary stack
                auxiliary.push(data);
            }
        }
        // Add remaining elements into actual stack
        while (auxiliary.isEmpty() == false)
        {
            // Add node
            this.stack.push(auxiliary.peek());
            // Remove node in auxiliary stack
            auxiliary.pop();
        }
    }
}

function main()
{
    var task = new DeleteOperation();
    // Add the stack element
    task.stack.push(5);
    task.stack.push(3);
    task.stack.push(5);
    task.stack.push(-3);
    task.stack.push(9);
    task.stack.push(-3);
    task.stack.push(4);
    task.stack.push(7);
    task.stack.push(-3);
    /*
    Created Stack
    ============

       -3 <- Top
        7
        4
       -3
        9
       -3
        5
        3
        5
    */
    process.stdout.write("\n Stack element \n");
    task.printData();
    var element = -3;
    // delete operation
    task.deleteNodes(element);
    /*
    After delete element -3 
    ============

        7 <- Top
        4
        9
        5
        3
        5
    */
    process.stdout.write("\n  After delete element " + element + " in stack \n");
    task.printData();
}
main();

Output

 Stack element
   -3   7   4   -3   9   -3   5   3   5

  After delete element -3 in stack
   7   4   9   5   3   5
#    Python 3 Program
#    Remove all particular element from a stack

#  Define stack node
class StackNode :
    
    def __init__(self, element, top) :
        self.element = element
        self.next = top
    

#  Define a custom stack
class MyStack :
    
    def __init__(self) :
        # Set node values
        self.top = None
        self.size = 0
    
    #  Add node at the top of stack
    def push(self, element) :
        self.top = StackNode(element, self.top)
        self.size += 1
    
    def isEmpty(self) :
        if (self.size > 0 and self.top != None) :
            return False
        else :
            return True
        
    
    #  Remove top element of stack
    def pop(self) :
        if (self.size > 0 and self.top != None) :
            temp = self.top
            #  Change top element of stack
            self.top = temp.next
            #  remove previous top
            temp = None
            self.size -= 1
        
    
    #  return top element of stack
    def peek(self) :
        return self.top.element
    

class DeleteOperation :
    
    def __init__(self) :
        self.stack = MyStack()
    
    #  Print element of stack
    def printData(self) :
        temp = self.stack.top
        while (temp != None) :
            #  Display element value
            print("   ", temp.element, end = "")
            temp = temp.next
        
        print(end = "\n")
    
    #  Remove specific element from stack
    def deleteNodes(self, element) :
        #  Create auxiliary stack
        auxiliary = MyStack()
        data = 0
        #  Executing the loop until when actual stack element are not empty
        while (self.stack.isEmpty() == False) :
            #  Get the top element of actual stack
            data = self.stack.peek()
            #  Remove top of current actual stack
            self.stack.pop()
            if (data != element) :
                #  When data is not equal to given deleted element
                #  Add data to auxiliary stack
                auxiliary.push(data)
            
        
        #  Add remaining elements into actual stack
        while (auxiliary.isEmpty() == False) :
            #  Add node
            self.stack.push(auxiliary.peek())
            #  Remove node in auxiliary stack
            auxiliary.pop()
        
    

def main() :
    task = DeleteOperation()
    task.stack.push(5)
    task.stack.push(3)
    task.stack.push(5)
    task.stack.push(-3)
    task.stack.push(9)
    task.stack.push(-3)
    task.stack.push(4)
    task.stack.push(7)
    task.stack.push(-3)
    # 
    #   Created Stack
    #    ============
    #   -3 <- Top
    #    7
    #    4
    #    -3
    #    9
    #    -3
    #    5
    #    3
    #    5
    #         
    
    print("\n Stack element ")
    task.printData()
    element = -3
    #  delete operation
    task.deleteNodes(element)
    # 
    #    After delete element -3 
    #    ============
    #    7 <- Top
    #    4
    #    9
    #    5
    #    3
    #    5
    #         
    
    print("\n  After delete element ", element ," in stack ")
    task.printData()

if __name__ == "__main__": main()

Output

 Stack element
    -3    7    4    -3    9    -3    5    3    5

  After delete element  -3  in stack
    7    4    9    5    3    5
#  Ruby Program
#  Remove all particular element from a stack

#  Define stack node
class StackNode  
	# Define the accessor and reader of class StackNode  
	attr_reader :element, :next
	attr_accessor :element, :next
 
	
	def initialize(element, top) 
		self.element = element
		self.next = top
	end

end

#  Define a custom stack
class MyStack  
	# Define the accessor and reader of class MyStack  
	attr_reader :top, :size
	attr_accessor :top, :size
 
	
	def initialize() 
		# Set node values
		self.top = nil
		self.size = 0
	end

	#  Add node at the top of stack
	def push(element) 
		self.top = StackNode.new(element, self.top)
		self.size += 1
	end

	def isEmpty() 
		if (self.size > 0 && self.top != nil) 
			return false
		else 
			return true
		end

	end

	#  Remove top element of stack
	def pop() 
		if (self.size > 0 && self.top != nil) 
			temp = self.top
			#  Change top element of stack
			self.top = temp.next
			#  remove previous top
			temp = nil
			self.size -= 1
		end

	end

	#  return top element of stack
	def peek() 
		return self.top.element
	end

end

class DeleteOperation  
	# Define the accessor and reader of class DeleteOperation  
	attr_reader :stack
	attr_accessor :stack
 
	
	def initialize() 
		self.stack = MyStack.new()
	end

	#  Print element of stack
	def printData() 
		temp = self.stack.top
		while (temp != nil) 
			#  Display element value
			print("   ", temp.element)
			temp = temp.next
		end

		print("\n")
	end

	#  Remove specific element from stack
	def deleteNodes(element) 
		#  Create auxiliary stack
		auxiliary = MyStack.new()
		data = 0
		#  Executing the loop until when actual stack element are not empty
		while (self.stack.isEmpty() == false) 
			#  Get the top element of actual stack
			data = self.stack.peek()
			#  Remove top of current actual stack
			self.stack.pop()
			if (data != element) 
				#  When data is not equal to given deleted element
				#  Add data to auxiliary stack
				auxiliary.push(data)
			end

		end

		#  Add remaining elements into actual stack
		while (auxiliary.isEmpty() == false) 
			#  Add node
			self.stack.push(auxiliary.peek())
			#  Remove node in auxiliary stack
			auxiliary.pop()
		end

	end

end

def main() 
	task = DeleteOperation.new()
	task.stack.push(5)
	task.stack.push(3)
	task.stack.push(5)
	task.stack.push(-3)
	task.stack.push(9)
	task.stack.push(-3)
	task.stack.push(4)
	task.stack.push(7)
	task.stack.push(-3)
	# 
	#         Created Stack
	#         ============
	#            -3 <- Top
	#             7
	#             4
	#            -3
	#             9
	#            -3
	#             5
	#             3
	#             5
	#         
	
	print("\n Stack element \n")
	task.printData()
	element = -3
	#  delete operation
	task.deleteNodes(element)
	# 
	#         After delete element -3 
	#         ============
	#             7 <- Top
	#             4
	#             9
	#             5
	#             3
	#             5
	#         
	
	print("\n  After delete element ", element ," in stack \n")
	task.printData()
end

main()

Output

 Stack element 
   -3   7   4   -3   9   -3   5   3   5

  After delete element -3 in stack 
   7   4   9   5   3   5
/*
   Scala Program
   Remove all particular element from a stack
*/
// Define stack node
class StackNode(var element: Int , var next: StackNode);
// Define a custom stack
class MyStack(var top: StackNode , var size: Int)
{
	def this()
	{
		this(null, 0);
	}
	// Add node at the top of stack
	def push(element: Int): Unit = {
		this.top = new StackNode(element, this.top);
		this.size += 1;
	}
	def isEmpty(): Boolean = {
		if (this.size > 0 && this.top != null)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	// Remove top element of stack
	def pop(): Unit = {
		if (this.size > 0 && this.top != null)
		{
			var temp: StackNode = this.top;
			// Change top element of stack
			this.top = temp.next;
			// remove previous top
			temp = null;
			this.size -= 1;
		}
	}
	// return top element of stack
	def peek(): Int = {
		return this.top.element;
	}
}
class DeleteOperation(var stack: MyStack)
{
	def this()
	{
		this(new MyStack());
	}
	// Print element of stack
	def printData(): Unit = {
		var temp: StackNode = this.stack.top;
		while (temp != null)
		{
			// Display element value
			print("   " + temp.element);
			temp = temp.next;
		}
		print("\n");
	}
	// Remove specific element from stack
	def deleteNodes(element: Int): Unit = {
		// Create auxiliary stack
		var auxiliary: MyStack = new MyStack();
		var data: Int = 0;
		// Executing the loop until when actual stack element are not empty
		while (this.stack.isEmpty() == false)
		{
			// Get the top element of actual stack
			data = this.stack.peek();
			// Remove top of current actual stack
			this.stack.pop();
			if (data != element)
			{
				// When data is not equal to given deleted element
				// Add data to auxiliary stack
				auxiliary.push(data);
			}
		}
		// Add remaining elements into actual stack
		while (auxiliary.isEmpty() == false)
		{
			// Add node
			this.stack.push(auxiliary.peek());
			// Remove node in auxiliary stack
			auxiliary.pop();
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: DeleteOperation = new DeleteOperation();
		// Add the stack element
		task.stack.push(5);
		task.stack.push(3);
		task.stack.push(5);
		task.stack.push(-3);
		task.stack.push(9);
		task.stack.push(-3);
		task.stack.push(4);
		task.stack.push(7);
		task.stack.push(-3);
		/*
		        Created Stack
		        ============

		           -3 <- Top
		            7
		            4
		           -3
		            9
		           -3
		            5
		            3
		            5
		        */
		print("\n Stack element \n");
		task.printData();
		var element: Int = -3;
		// delete operation
		task.deleteNodes(element);
		/*
		        After delete element -3 
		        ============

		            7 <- Top
		            4
		            9
		            5
		            3
		            5
		        */
		print("\n  After delete element " + element + " in stack \n");
		task.printData();
	}
}

Output

 Stack element
   -3   7   4   -3   9   -3   5   3   5

  After delete element -3 in stack
   7   4   9   5   3   5
/*
   Swift 4 Program
   Remove all particular element from a stack
*/
// Define stack node
class StackNode
{
    var element: Int;
    var next: StackNode? ;
    init(_ element: Int, _ top: StackNode? )
    {
        self.element = element;
        self.next = top;
    }
}
// Define a custom stack
class MyStack
{
    var top: StackNode? ;
    var size: Int;
    init()
    {
        //Set node values
        self.top = nil;
        self.size = 0;
    }
    // Add node at the top of stack
    func push(_ element: Int)
    {
        self.top = StackNode(element, self.top);
        self.size += 1;
    }
    func isEmpty()->Bool
    {
        if (self.size > 0 && self.top != nil)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    func pop()
    {
        if (self.size > 0 && self.top != nil)
        {
            var temp: StackNode? = self.top;
            // Change top element of stack
            self.top = temp!.next;
            // remove previous top
            temp = nil;
            self.size -= 1;
        }
    }
    // return top element of stack
    func peek()->Int
    {
        return self.top!.element;
    }
}
class DeleteOperation
{
    var stack: MyStack;
    init()
    {
        self.stack = MyStack();
    }
    // Print element of stack
    func printData()
    {
        var temp: StackNode? = self.stack.top;
        while (temp != nil)
        {
            // Display element value
            print("   ", temp!.element, terminator: "");
            temp = temp!.next;
        }
        print(terminator: "\n");
    }
    // Remove specific element from stack
    func deleteNodes(_ element: Int)
    {
        // Create auxiliary stack
        let auxiliary: MyStack = MyStack();
        var data: Int = 0;
        // Executing the loop until when actual stack element are not empty
        while (self.stack.isEmpty() == false)
        {
            // Get the top element of actual stack
            data = self.stack.peek();
            // Remove top of current actual stack
            self.stack.pop();
            if (data != element)
            {
                // When data is not equal to given deleted element
                // Add data to auxiliary stack
                auxiliary.push(data);
            }
        }
        // Add remaining elements into actual stack
        while (auxiliary.isEmpty() == false)
        {
            // Add node
            self.stack.push(auxiliary.peek());
            // Remove node in auxiliary stack
            auxiliary.pop();
        }
    }
}
func main()
{
    let task: DeleteOperation = DeleteOperation();
    // Add the stack element
    task.stack.push(5);
    task.stack.push(3);
    task.stack.push(5);
    task.stack.push(-3);
    task.stack.push(9);
    task.stack.push(-3);
    task.stack.push(4);
    task.stack.push(7);
    task.stack.push(-3);
    /*
    Created Stack
    ============

       -3 <- Top
        7
        4
       -3
        9
       -3
        5
        3
        5
    */
    print("\n Stack element ");
    task.printData();
    let element: Int = -3;
    // delete operation
    task.deleteNodes(element);
    /*
    After delete element -3 
    ============

        7 <- Top
        4
        9
        5
        3
        5
    */
    print("\n  After delete element ", element ," in stack ");
    task.printData();
}
main();

Output

 Stack element
    -3    7    4    -3    9    -3    5    3    5

  After delete element  -3  in stack
    7    4    9    5    3    5
/*
   Kotlin Program
   Remove all particular element from a stack
*/
// Define stack node
class StackNode
{
    var element: Int;
    var next: StackNode ? ;
    constructor(element: Int, top: StackNode ? )
    {
        this.element = element;
        this.next = top;
    }
}
// Define a custom stack
class MyStack
{
    var top: StackNode ? ;
    var size: Int;
    constructor()
    {
        //Set node values
        this.top = null;
        this.size = 0;
    }
    // Add node at the top of stack
    fun push(element: Int): Unit
    {
        this.top = StackNode(element, this.top);
        this.size += 1;
    }
    fun isEmpty(): Boolean
    {
        if (this.size>0 && this.top != null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Remove top element of stack
    fun pop(): Unit
    {
        if (this.size>0 && this.top != null)
        {
            var temp: StackNode ? = this.top;
            // Change top element of stack
            this.top = temp?.next;
            this.size -= 1;
        }
    }
    // return top element of stack
    fun peek(): Int
    {
        return this.top!!.element;
    }
}
class DeleteOperation
{
    var stack: MyStack;
    constructor()
    {
        this.stack = MyStack();
    }
    // Print element of stack
    fun printData(): Unit
    {
        var temp: StackNode ? = this.stack.top;
        while (temp != null)
        {
            // Display element value
            print("   " + temp.element);
            temp = temp.next;
        }
        print("\n");
    }
    // Remove specific element from stack
    fun deleteNodes(element: Int): Unit
    {
        // Create auxiliary stack
        var auxiliary: MyStack = MyStack();
        var data: Int ;
        // Executing the loop until when actual stack element are not empty
        while (this.stack.isEmpty() == false)
        {
            // Get the top element of actual stack
            data = this.stack.peek();
            // Remove top of current actual stack
            this.stack.pop();
            if (data != element)
            {
                // When data is not equal to given deleted element
                // Add data to auxiliary stack
                auxiliary.push(data);
            }
        }
        // Add remaining elements into actual stack
        while (auxiliary.isEmpty() == false)
        {
            // Add node
            this.stack.push(auxiliary.peek());
            // Remove node in auxiliary stack
            auxiliary.pop();
        }
    }
}
fun main(args: Array<String>): Unit
{
    var task: DeleteOperation = DeleteOperation();
    // Add the stack element
    task.stack.push(5);
    task.stack.push(3);
    task.stack.push(5);
    task.stack.push(-3);
    task.stack.push(9);
    task.stack.push(-3);
    task.stack.push(4);
    task.stack.push(7);
    task.stack.push(-3);
    /*
    Created Stack
    ============

       -3 <- Top
        7
        4
       -3
        9
       -3
        5
        3
        5
    */
    print("\n Stack element \n");
    task.printData();
    var element: Int = -3;
    // delete operation
    task.deleteNodes(element);
    /*
    After delete element -3 
    ============

        7 <- Top
        4
        9
        5
        3
        5
    */
    print("\n  After delete element " + element + " in stack \n");
    task.printData();
}

Output

 Stack element
   -3   7   4   -3   9   -3   5   3   5

  After delete element -3 in stack
   7   4   9   5   3   5

Time Complexity

The time complexity of the deleteNodes() function is O(N), where N is the number of elements in the stack. This is because each element is visited once, and each element is either pushed or popped from the auxiliary stack and then pushed back into the original stack. Therefore, the overall time complexity of the deletion process is O(N).





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment