w3resource

C#: Check if a stack is a subset of another stack

C# Sharp Stack: Exercise-18 with Solution

Write a C# program that implements a stack and checks if a stack is a subset of another stack.

Sample Solution:

C# Code:

using System;
using System.Collections;
using System.Collections.Generic;

public class Stack
{
    private int[] items; // Array to hold stack elements
    private int top; // Index indicating the top of the stack

    // Constructor to initialize the stack with a specified size
    public Stack(int size)
    {
        items = new int[size]; // Creating an array of integers with the given size
        top = -1; // Initializing top index to -1 indicating an empty stack
    }

    // Check if the stack is empty
    public bool IsEmpty()
    {
        return top == -1; // Stack is empty if top is -1
    }

    // Check if the stack is full
    public bool IsFull()
    {
        return top == items.Length - 1; // Stack is full if top equals the last index of the array
    }

    // Push an element onto the stack
    public void Push(int item)
    {
        if (IsFull()) // Check if the stack is full
        {
            Console.WriteLine("Stack Full!"); // Display a message indicating stack overflow
            return;
        }

        items[++top] = item; // Increment top and add the item to the stack
    }

    // Pop an element from the stack
    public int Pop()
    {
        if (IsEmpty()) // Check if the stack is empty
        {
            Console.WriteLine("Stack underflow"); // Display a message indicating stack underflow
            return -1;
        }

        return items[top--]; // Return and decrement top to remove the element from the stack
    }

    // Peek at the top element of the stack without removing it
    public int Peek()
    {
        if (IsEmpty()) // Check if the stack is empty
        {
            Console.WriteLine("Stack is empty"); // Display a message indicating the stack is empty
            return -1;
        }

        return items[top]; // Return the top element of the stack
    }

    // Static method to get the size of a stack
    public static int Size(Stack stack)
    {
        return stack.top + 1; // Return the size of the stack based on the current top index
    }

    // Static method to count all the elements in a stack
    public static int Count(Stack stack)
    {
        int count = 0; // Initialize count variable to track the number of elements

        Stack temp = new Stack(Size(stack)); // Create a temporary stack to preserve the original stack order

        // Move elements from the original stack to the temporary stack and count them
        while (!stack.IsEmpty())
        {
            temp.Push(stack.Pop()); // Move elements from original stack to temporary stack
            count++; // Increment count for each element moved
        }

        // Restore the original stack by moving elements back from the temporary stack
        while (!temp.IsEmpty())
        {
            stack.Push(temp.Pop()); // Move elements back to the original stack
        }

        return count; // Return the total count of elements in the stack
    }

    // Static method to clear the stack by popping all elements
    public static void Clear(Stack stack)
    {
        while (!stack.IsEmpty())
        {
            stack.Pop(); // Remove elements from the stack until it's empty
        }
    }

    // Method to check if an element is present or not in a stack
    public static bool Contains(Stack stack, int item)
    {
        if (stack == null || stack.IsEmpty())
            return false;

        bool found = false;
        Stack tempStack = new Stack(Size(stack));

        // Check if the stack contains the specified item
        while (!stack.IsEmpty())
        {
            int current = stack.Pop();
            if (current == item)
            {
                found = true;
                break;
            }
            tempStack.Push(current);
        }

        // Restore the original stack by moving elements back from the temporary stack
        while (!tempStack.IsEmpty())
        {
            stack.Push(tempStack.Pop());
        }

        return found; // Return whether the item was found in the stack
    }

    // Check if a stack is a subset of another stack
    public static bool IsSubset(Stack first, Stack second)
    {
        if (first == null || second == null) return false;

        Stack temp = new Stack(Size(first));

        // Check if the first stack is a subset of the second stack
        while (!first.IsEmpty())
        {
            int current = first.Pop();

            if (!Contains(second, current)) return false;

            temp.Push(current);
        }

        // Restore the original first stack by moving elements back from the temporary stack
        while (!temp.IsEmpty())
        {
            first.Push(temp.Pop());
        }

        return true; // Return true if the first stack is a subset of the second stack
    }

    // Method to display the elements of the stack
    public static void Display(Stack stack)
    {
        if (stack.IsEmpty()) // Check if the stack is empty
        {
            Console.WriteLine("Stack is empty"); // Display a message indicating the stack is empty
            return;
        }

        Console.WriteLine("Stack elements:"); // Display a message indicating stack elements will be shown
        for (int i = stack.top; i >= 0; i--) // Loop through the stack elements
        {
            Console.Write(stack.items[i] + " "); // Print each element of the stack
        }
    }

}

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Initialize a stack:");
        Stack stack1 = new Stack(6); // Create stack1 with a capacity of 6 elements
        stack1.Push(1);
        stack1.Push(2);
        stack1.Push(3);
        stack1.Push(4);
        stack1.Push(5);
        stack1.Push(6);
        Console.WriteLine("\nStack-1");
        Stack.Display(stack1); // Display elements of stack1

        Stack stack2 = new Stack(3); // Create stack2 with a capacity of 3 elements
        stack2.Push(1);
        stack2.Push(2);
        stack2.Push(3);
        Console.WriteLine("\nStack-2");
        Stack.Display(stack2); // Display elements of stack2

        Console.WriteLine("\nIf stack2 is a subset of stack1!");
        bool result = Stack.IsSubset(stack2, stack1); // Check if stack2 is a subset of stack1
        Console.WriteLine("{0}", result);

        Console.WriteLine("\nIf stack1 is a subset of stack2!");
        result = Stack.IsSubset(stack1, stack2); // Check if stack1 is a subset of stack2
        Console.WriteLine("{0}", result);
    }
}

Sample Output:

Initialize a stack:

Stack-1
Stack elements:
6 5 4 3 2 1
Stack-2
Stack elements:
3 2 1
If stack2 is a subset of stack1!
True

If stack1 is a subset of stack2!
False

Flowchart:

Flowchart: Check if a stack is a subset of another stack.
Flowchart: Check if a stack is a subset of another stack.
Flowchart: Check if a stack is a subset of another stack.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Merge two stacks into one.
Next: Checks if two stacks are equal.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/csharp-exercises/stack/csharp-stack-exercise-18.php