c# - Understanding how queue/stack class works and figuring out why this code isn't working -
c# - Understanding how queue/stack class works and figuring out why this code isn't working -
the first foreach method gets several errors. can't figure out why , seems should work...
foreach - invalid token 'foreach' in class, struct, or interface fellow member declaration.
this prints out 1 2 3 4 1 2 3 4 1 2 3 4.
the 2nd foreach method. how work? think iterates through each number 1 @ time in order. confusion comes in same code, stack instead of queue. 2nd foreach prints out 4 3 2 1. why this?
namespace cards { class class1 { queue numbers = new queue(); foreach (int number in new int[4]{1,2,3,4}) { numbers.enqueue(number); console.writeline(number + " has joined queue"); } foreach (int number in numbers) { console.writeline(number); } while(numbers.count > 0) { int number = (int)numbers.dequeue(); console.writeline(number + " has left queue"); } } }
that code needs in method..
class class1 { public void doqstuff() { queue numbers = new queue(); foreach (int number in new int[4]{1,2,3,4}) { numbers.enqueue(number); console.writeline(number + " has joined queue"); } foreach (int number in numbers) { console.writeline(number); } while(numbers.count > 0) { int number = (int)numbers.dequeue(); console.writeline(number + " has left queue"); } } }
and whole thing works expected if run it
queues work, first in, first out..... 1 first in, first out
stacks work, first in, lastly out, 1 first thing in, lastly thing out
like, if line served @ coffee shop, have wait in queue till turn, first person in queue, first person served.
stacks stacking books on top of each other....you can't take first thing off stack until unstack things on top of it.
c#
Comments
Post a Comment