15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

linked list ❘ 241<br />

{<br />

Console.Write(item);<br />

}<br />

Console.WriteLine();<br />

code snippet StackSample/Program.cs<br />

Because the items are read in order from the last added to the first, the following result is produced:<br />

CBA<br />

Reading the items with the enumerator does not change the state of the items. With the Pop() method,<br />

every item that is read is also removed from the stack. This way you can iterate the collection using a while<br />

loop <strong>and</strong> verify the Count property if items still exist:<br />

var alphabet = new Stack();<br />

alphabet.Push('A');<br />

alphabet.Push('B');<br />

alphabet.Push('C');<br />

Console.Write("First iteration: ");<br />

foreach (char item in alphabet)<br />

{<br />

Console.Write(item);<br />

}<br />

Console.WriteLine();<br />

Console.Write("Second iteration: ");<br />

while (alphabet.Count > 0)<br />

{<br />

Console.Write(alphabet.Pop());<br />

}<br />

Console.WriteLine();<br />

The result gives CBA twice, once for each iteration. After the second iteration, the stack is empty because<br />

the second iteration used the Pop() method:<br />

First iteration: CBA<br />

Second iteration: CBA<br />

tinKed lisT<br />

LinkedList is a doubly linked list, where one element references the next <strong>and</strong> the previous one, as<br />

shown in Figure 10-3.<br />

Value<br />

Value<br />

Value<br />

Value<br />

Next<br />

Next<br />

Next<br />

Next<br />

Previous<br />

Previous<br />

Previous<br />

Previous<br />

figure 10-3<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!