The stack has multiple types. In this section, we will discuss the first type, which represents the stack as an array that operates based on the LIFO (Last In, First Out) principle — the last element inserted is the first one to be removed. اخر عنصر بيدخل هو اول عنصر بيخرج
الستاك هو عبارة عن وعاء وبيستوعب مجموعة من العناصر وكل عنصر يكون مرتب فوق العنصر اللي قبله. وقت كنا نعرف المصفوفة نعطيها حجم معين والستاك أيضا نفس الشي ولكن بخواص محددة
Array and Stack
Adding an element to the stack
Printing the first element
طيب شو اللي بساعدنا بعملية الأضافة، كيف بدنا نضمن انو نضيف بعد اخر عنصر وليس قبله؟ بالستاك في شي اسمه top
وهو مؤشر أو متغير يقلنا وين نحنا حاليا بالستاك، بحيث بس بدنا نضيف عنصر نضمن بعد اضافته انو نغير مكان تأشيره لاخر عنصر
top
is the index of the stack. Initial value of the top = -1
when the stack is empty.
printing the first element with top pointer
Adding more elements, now the stack is full
Adding an element, and top moves towards up
When we delete element, the last added one will be deleted automatically, and top will decrease it’s value.
وقت حذف أو طباعة أي عنصر رح يتأثر فيها أول عنصر على قمة الستاك، واللي هو اخر واحد تم اضافته على الستاك.
التوب مكانها ما بيتخربط او ما عندها فرصة مثلا بدل ما تنزل لل20 تروح لل15. يعني مثلا لو بدنا نوصل لاول عنصر تم اضافته على الستاك لازم نمسح كل اللي قبله لنوصله. مافي طريقة تانية
When we’re typing a sentence and we delete a character by mistake, we immediately click Ctrl + Z , but how does this work under the hood?
All character gets added to the Stack
Delete the last element by mistake
Restores the last added character with help of Stack
When you navigating web and want to go back in tabs. Stack stores address of each webpage you visit and when you press back it takes you to the latest stored URL in the top
push(val)
لادخال قيمةpop()
لحذف اخر عنصر تم اضافته على الستاكtop
or getTop()
لنرجع قيمة العنصر اللي هو بقمة الستاك