Skip to content

39. The Classes Stack and Queue

February 14, 2011

The class Stack implements a pile, a pile of pancakes and the class Queue implements a line, waiting line in a bank. The pile and line can contain objects of different types.

Principle of a pile: the object is always put on the top of the pile, and only the object at the top can be retrieved.
Access to the pile happens in a LIFO(Last In, First Out), or last one added, first one selected.

Principle of a line: the object is always laid on the top of the pile and only the bottom most one can be retrieved.
Access to the line is FIFO(First In, First Out), or first one entered, first one out.

The pile and line grow automatically based on the additions and removals of objects.

The classes Stack and Queue implement the interface ICollection.

Insert an object
Only one method permits to add an object to the pile:

  • void Push(Object obj)

Only one method permits to add an object to the line:

  • void Enqueue(Object obj)

Return and removal of an object

  • object Pop()
    Removes and returns the object at the top of the stack.
  • object Dequeue()
    Removes and returns the object at the beginning of the queue.
  • object Peek()
    Returns the object at the top/beginning without removing it.
  • Object[] ToArray()
    Returns a copy of the stack as an array.
  • void Clear()
    Empties the stack or the queue of all elements.

The class System.Collections.Generic.Queue<T>

Based on the same behavior as the non generic class Queue in the namespace System.Collections.
The class Queue<T> implements the interfaces ICollection, IEnumerable, IEnumerable<T>.
It contains the following members:

  • void Enqueue(T item)
  • T Dequeue()
  • T Peek()

The class System.Collections.Generic.Stack<T>

Based on the same behavior as the non generic class Stack in the namespace System.Collections.

The class Stack<T> implements the interfaces ICollection, IEnumerable and IEnumerable<T>.
It contains the following members:

  • void Push(T item)
  • T Pop()
  • T Peek()

Happy Programing! =)

Advertisements

From → OOP

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: