w3resource

C#: New stack from a portion of the original stack


Write a C# program that implements a stack and creates a new stack from a portion of the original stack.

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
    }

    // Method to create a new stack from the original stack within a specified range
    public static Stack new_stack_from_original(Stack original, int start, int end)
    {
        if (start < 0 || end >= Size(original) || start > end)
        {
            Console.WriteLine("Invalid start or end index."); // Display an error message for invalid indices
            return null;
        }

        int newSize = end - start + 1;
        Stack newStack = new Stack(newSize);
        Stack temp = new Stack(Size(original));

        // Pop elements until reaching the start index
        while (original.top > start - 1)
        {
            temp.Push(original.Pop());
        }

        // Push elements from the original stack to the new stack within the specified range
        for (int i = 0; i < newSize; i++)
        {
            newStack.Push(temp.Pop());
        }

        // Push back elements into the original stack
        while (!temp.IsEmpty())
        {
            original.Push(temp.Pop());
        }

        return newStack; // Return the new stack with elements from the specified range of the original stack
    }

    // Method to display the elements of the stack

    public static void Display(Stack stack)
    {
        if (stack.IsEmpty())
        {
            Console.WriteLine("Stack is empty"); // Display a message if the stack is empty
            return;
        }

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

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Initialize three stacks:");
        Stack stack1 = new Stack(10);
        stack1.Push(1);
        stack1.Push(2);
        stack1.Push(3);
        stack1.Push(4);
        stack1.Push(5);
        stack1.Push(6);
        Stack.Display(stack1); // Display the original stack

        Console.WriteLine("\n\nCreate a new stack from stack1 (from index 0 to 4):");
        Stack newStack = Stack.new_stack_from_original(stack1, 0, 4); // Create a new stack from the original stack
        Console.Write("New stack:\n");
        Stack.Display(newStack); // Display the new stack
    }
}

Sample Output:

Initialize three stacks:
Stack elements:
6 5 4 3 2 1

Create a new stack from stack1 (from index 0 to 4):
New stack:
Stack elements:
5 4 3 2 1

Flowchart:

Flowchart: New stack from a portion of the original stack.
Flowchart: New stack from a portion of the original stack.
Flowchart: New stack from a portion of the original stack.

C# Sharp Code Editor:



Improve this sample solution and post your code through Disqus

Previous: Symmetric difference of two stacks.
Next: Verify all stack elements satisfy a condition.

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.