0

How this codes work, especially on "word+=letters.pop()" and "word+=letters.Peek()"? Anyone can help?

using System; using System.Collections.Generic; namespace SoloLearn { class Program { static void Main(string[] args) { string word =" "; Stack<string> letters = new Stack<string>(); letters.Push("o"); letters.Push("l"); letters.Push("e"); letters.Push("h"); word+=letters.Pop(); word+=letters.Pop(); word+=letters.Peek(); word+=letters.Pop(); word+=letters.Pop(); Console.Write(word); } } }

17th May 2020, 6:08 AM
Irezer
Irezer - avatar
2 Answers
+ 1
So first "o" is pushed into the stack so it is at index 0 in stack and then "l" is pushed so it is at index 1 and so on It's now h e l o now pop returns and remove the topmost element in stack word=word+letters.pop() Is word=""+h word="h" now and only these letters are left in stack e l o then word="h"+ letters.pop() word="h"+"e" word="he" so stack now contains l o and now peek method doesn't removes the element It just returns it so string word will be now "hel" while stack still contains l o
17th May 2020, 6:22 AM
Abhay
Abhay - avatar
0
thanks for the clarification 👍
18th May 2020, 3:11 PM
Irezer
Irezer - avatar