w3resource

C#: Symmetric difference of two stacks

C# Sharp Stack: Exercise-23 with Solution

Write a C# program that implements a stack and creates a new stack that contains only elements that are in either the first or the second stack, but not in both.

In mathematics, the symmetric difference of two sets, also known as the disjunctive union, is the set of elements which are in either of the sets, but not in their intersection. For example, the symmetric difference of the sets {1,2,3} and {3,4} is {1,2,3}

Sample Solution:

C# Code:

using System;
using System.Collections.Generic;

public class Stack
{
    private int[] items; // Array to store stack elements
    private int top; // Index indicating the top element in the stack

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

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

    // Check if the stack is full
    public bool IsFull()
    {
        return top == items.Length - 1; // Returns true if the stack is full
    }

    // 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
    }

    // Method to count all the elements in a stack
    public static int Count(Stack stack)
    {
        int count = 0;
        Stack temp = new Stack(Size(stack));

        // Move elements from the original stack to a temporary stack and count them
        while (!stack.IsEmpty())
        {
            temp.Push(stack.Pop()); // Move elements from the original stack to the 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
    }   

    // Check if an element exists in the stack
    public bool Contains(int item)
    {
        for (int i = 0; i <= top; i++)
        {
            if (items[i] == item)
            {
                return true; // Return true if the element is found in the stack
            }
        }

        return false; // Return false if the element is not found in the stack
    }

    // Method to get the symmetric difference between two stacks
    public static Stack Symmetric_difference(Stack stack1, Stack stack2)
    {
        int combinedSize = Size(stack1) + Size(stack2);
        Stack result = new Stack(combinedSize);

        // Find elements in stack1 not present in stack2 and vice versa without duplicates
        for (int i = 0; i <= stack1.top; i++)
        {
            int item = stack1.items[i];
            if (!stack2.Contains(item) && !result.Contains(item))
            {
                result.Push(item);
            }
        }

        for (int i = 0; i <= stack2.top; i++)
        {
            int item = stack2.items[i];
            if (!stack1.Contains(item) && !result.Contains(item))
            {
                result.Push(item);
            }
        }

        return result; // Return the stack containing symmetric difference elements
    }

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

        Console.WriteLine("Stack elements:");
        for (int i = stack.top; i >= 0; i--)
        {
            Console.Write(stack.items[i] + " ");
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Initialize three stacks:");

        // Create and display stack1
        Stack stack1 = new Stack(10);
        stack1.Push(1);
        stack1.Push(2);
        stack1.Push(3);
        Console.Write("Stack1: ");
        Stack.Display(stack1);

        // Create and display stack2
        Stack stack2 = new Stack(10);
        stack2.Push(2);
        stack2.Push(3);
        stack2.Push(4);
        stack2.Push(5);
        Console.Write("\nStack2: ");
        Stack.Display(stack2);

        // Create and display stack3
        Stack stack3 = new Stack(10);
        stack3.Push(3);
        stack3.Push(4);
        stack3.Push(5);
        Console.Write("\nStack3: ");
        Stack.Display(stack3);

        // Get the symmetric difference between stack1 and stack2 and display the result
        Stack result = Stack.Symmetric_difference(stack1, stack2);
        Console.Write("\n\nSymmetric difference stack1 and stack2:\n");
        Stack.Display(result);

        // Get the symmetric difference between stack2 and stack3 and display the result
        result = Stack.Symmetric_difference(stack2, stack3);
        Console.Write("\n\nSymmetric difference of stack2 and stack3:\n");
        Stack.Display(result);

        // Get the symmetric difference between stack3 and stack1 and display the result
        result = Stack.Symmetric_difference(stack3, stack1);
        Console.Write("\n\nSymmetric difference of stack3 and stack1:\n");
        Stack.Display(result);
    }
}

Sample Output:

Initialize three stacks:
Stack1: Stack elements:
3 2 1
Stack2: Stack elements:
5 4 3 2
Stack3: Stack elements:
5 4 3

Symmetric difference stack1 and stack2:
Stack elements:
5 4 1

Symmetric difference of stack2 and stack3:
Stack elements:
2

Symmetric difference of stack3 and stack1:
Stack elements:
2 1 5 4

Flowchart:

Flowchart: Symmetric difference of two stacks.
Flowchart: Symmetric difference of two stacks.
Flowchart: Symmetric difference of two stacks.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Elements from both stacks without duplicates.
Next: New stack from a portion of the original stack.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.