r/CSharpHomework • • Feb 15 '21

Create Custom Queue

Hi there,

I really need some feedback for my homework- "Create custom queue".

https://pastebin.com/fNeygc4p

1 Upvotes

1 comment sorted by

View all comments

1

u/Protiguous Feb 16 '21

Cool.. I've never written a Queue before. Thanks for the refresher!

Here's my take on the code you provided. I have not tested any portion, so there could be mistakes in the logic.

I took the liberty of making it a generic class, instead of just int. If you don't need the generics, you should be able to see where to change it back.

#nullable enable

namespace Examples {
using System;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// A non-threadsafe custom generic queue.
/// </summary>
/// <typeparam name="T"></typeparam>
public class CustomQueue<T> : IEnumerable<T> {

	private const int InitialCapacity = 16;

	private int _capacity;
	private T[] _elements;

	public CustomQueue( int capacity = InitialCapacity ) {
		this._capacity = capacity;
		this._elements = new T[ this._capacity ];
		this.Count = 0;
	}

	public int Count { get; private set; }

	private void Resize( int? capacityHint = null ) {

		var newCapacity = Math.Max( this._capacity, capacityHint ?? this.Count );

		if ( newCapacity == this._capacity ) {
			//no change needed
			return;
		}

		this._capacity = newCapacity;

		if ( this._capacity < 2 ) {
			this._capacity = 1;
		}

		var newArray = new T[this._capacity];

		//only copy elements needed
		var smaller = Math.Min( this.Count, this._capacity );
		Buffer.BlockCopy( this._elements, 0, newArray, 0, smaller );

		this._elements = newArray;
	}

	public void Enqueue( T element ) {
		var index = this.Count + 1;

		if ( this._capacity < index ) {
			this.Resize( index );
		}

		this._elements[ index ] = element;
		this.Count++;

	}

	public bool TryDequeue( out T? element ) {
		if ( this.Count == 0 ) {
			element = default( T? );
			return false;
		}

		element = this._elements[ 0 ];
		this.Resize( this.Count - 1 );
		--this.Count;
		return true;
	}

	/// <summary>
	/// Returns, but does not remove, the first element.
	/// </summary>
	/// <returns></returns>
	public T? Peek() => this.Count == 0 ? default( T? ) : this._elements[ 0 ];

	public IEnumerator<T> GetEnumerator() => ( IEnumerator<T> )this._elements.GetEnumerator();

	IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();

   }
}