#843 – Using the Generic Stack Class
May 14, 2013 Leave a comment
A stack is a data structure that allows adding elements to the top of the stack through a Push operation, or removing elements from the top of the stack through a Pop operation.
The .NET Framework includes a Stack<T> type, defined in System.Collections.Generic, that implements a stack data type.
When you declare a stack, you indicate the type of objects that the stack will contain.
Stack<Book> pileOfBooks = new Stack<Book>();
You can now add instances of Books to the top of the stack using the Push method.
// Push 1st book onto stack pileOfBooks.Push(new Book("The World According to Garp", new Person("Irving", "John"))); // Push another. Gatsby on "top" of stack pileOfBooks.Push(new Book("The Great Gatsby", new Person("Fitzgerald", "F. Scott")));
You can remove the object from the stop of the stack using the Pop method.
// Remove book from top Book bookToRead = pileOfBooks.Pop(); Console.WriteLine(bookToRead);