Answer the question
In order to leave comments, you need to log in
How to implement a stack in C#?
Using only using System;
Answer the question
In order to leave comments, you need to log in
For example, like this:
public class SimpleSystemStack<T> where T : struct, IConvertible {
private readonly int _sizeOfOneElement;
private T[] _array;
public SimpleSystemStack( int sizeOfOneElement, T[] inputArray = null ) {
_sizeOfOneElement = sizeOfOneElement;
if ( inputArray?.Length > 0 ) {
Length = inputArray.Length;
_array = inputArray;
} else {
Length = 0;
_array = new T[sizeOfOneElement];
}
}
public int Length { get; private set; }
public T Pop() {
if ( Length > 0 ) {
Length--;
return _array[Length];
}
throw new IndexOutOfRangeException("Stack is Empty.");
}
public void Push( T element ) {
if ( Length >= int.MaxValue )
throw new IndexOutOfRangeException("Stack overflow.");
if ( Length >= _array.Length ) {
var temp = new T[_array.Length * 2];
Buffer.BlockCopy( _array, 0, temp, 0, Length * _sizeOfOneElement );
_array = temp;
}
_array[Length] = element;
Length++;
}
}
var sss = new SimpleSystemStack<int>( sizeof( int ) );
sss.Push( 1 );
sss.Push( 2 );
sss.Push( 3 );
sss.Pop();
sss.Pop();
sss.Push( 4 );
what? Google already blocked too? stack in C#
ps I remembered, there was a question about optimizing the stack, somewhere in January 2017 , people there painted everything on the classes, but speed was the priority))). but there was also a requirement for stack modification functions .. it turned out I still had project. here is the code (System.Diagnostics is needed to measure execution time)
using System;
using System.Diagnostics;
namespace stack
{
public class Program
{
static private int max = 100_000_000;
class Stack
{
private int[] sd = new int[max];
private int sp = -1;
public void Push(int data) => sd[++sp] = data;
public int Pop() => sd[sp--];
public void Rep(int sp, int data) => sd[sp] = data;
public void Inc(int sp, int data) => sd[sp] += data;
public void Dec(int sp, int data) => sd[sp] -= data;
public void Xor(int sp, int data) => sd[sp] %= data;
}
public static void StackTest()
{
var watch = new Stopwatch();
var stack = new Stack();
var count = max;
watch.Start();
for (int i = 0; i < count; i++)
stack.Push(i);
watch.Stop();
Console.WriteLine(watch.Elapsed);
watch.Restart();
for (int i = 0; i < count; i++)
stack.Xor(i, 2);
watch.Stop();
Console.WriteLine(watch.Elapsed);
watch.Restart();
for (int i = 0; i < count; i++)
stack.Pop();
watch.Stop();
Console.WriteLine(watch.Elapsed);
Console.ReadKey();
}
public static void Main() => StackTest();
}
}
bool empty() => sp < 0;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question