Lila25mila
March 11, 2019, 3:28 p.m.

Stack

Stack concept

The stack is a useful data structure in programming. It's like a stack of plates stacked on top of each other.


Think about what you can do with such a bunch of plates:

  • Put a new plate on top;
  • Move the top plate.

If you want the plate to be at the bottom, you must remove all the top plates. This arrangement is called Last In First Out or LIFO (last in, first out) - the last element that is put in is the first element to come out.

Stack in programming conditions

In terms of programming, placing an element on top of the stack is called "push" and removing an element is called "pop". The last element added is called the top of the stack, or "top".

In the image, you can see that element 2 was saved last, but is removed first, as it obeys the LIFO (last in, first out) principle.

We can implement a stack in any programming language like C, C++, Java, Python or C# with almost the same specification.

Stack Specification

A stack is an object, or more specifically an abstract data structure (ADT), that allows you to perform the following operations:

  • Push: add an element to the top of the stack;
  • Pop: remove an element from the top of the stack;
  • IsEmpty: check if the stack is empty;
  • IsFull: check if the stack is full;
  • Peek: Get the value of the top element without removing it.
How the stack works

Operations work like this:

  1. The TOP pointer is called to keep track of the top element on the stack.
  2. When initializing the stack, we set its value to -1 so that we can check if the stack is empty by comparing TOP == -1.
  3. By clicking on an element, we increment the value of TOP and place the new element at the position pointed to by TOP.
  4. When we get an element, we return the element pointed to by TOP and decrement its value.
  5. Before adding an element, we check if the stack is full.
  6. Before removing an element, we check if the stack is empty.

Implementing a stack in a programming language

The most common implementation of a stack uses arrays, but implementations using lists are also possible.

Here is an implementation using arrays in C.

  1. #include<stdio.h>
  2. #include<conio.h>
  3. #include<stdlib.h>
  4.  
  5. #define MAX 10
  6.  
  7. struct stack
  8. {
  9. int items[MAX];
  10. int top;
  11. };
  12. typedef struct stack st;
  13.  
  14. void createEmptyStack(st *s)
  15. {
  16. s->top=-1;
  17. }
  18.  
  19. int isfull(st *s)
  20. {
  21. if (s->top==MAX-1)
  22. return 1;
  23. else
  24. return 0;
  25. }
  26.  
  27. int isempty(st *s)
  28. {
  29. if (s->top==-1)
  30. return 1;
  31. else
  32. return 0;
  33. }
  34.  
  35. void push(st *s)
  36. {
  37. int newitem;
  38. printf("Enter item to be inserted: ");
  39. scanf("%d",&newitem);
  40. if (isfull(s))
  41. {
  42. printf("STACK FULL");
  43. }
  44. else
  45. {
  46. s->top++;
  47. s->items[s->top]=newitem;
  48. }
  49. }
  50.  
  51.  
  52. void pop (st *s)
  53. {
  54. if (isempty(s))
  55. {
  56. printf("\n STACK EMPTY \n");
  57. }
  58. else
  59. {
  60. printf("Item popped= %d",s->items[s->top]);
  61. s->top--;
  62. }
  63. }
  64.  
  65. void main()
  66. {
  67. int ch;
  68. int loop;
  69. loop=1;
  70. st *s;
  71.  
  72. createEmptyStack(s);
  73.  
  74. do
  75. {
  76. printf("\n ***STACK OPERATIONS");
  77. printf("\n 1. PUSH");
  78. printf("\n 2. POP");
  79. printf("\n 3. EXIT");
  80. printf("\n ***************");
  81. printf("\n Enter your choice: ");
  82. scanf("%d", &ch);
  83.  
  84. switch (ch)
  85. {
  86. case 1:
  87. push(s);
  88. break;
  89. case 2:
  90. pop(s);
  91. break;
  92. case 3:
  93. printf("THANK YOU");
  94. loop=0;
  95. exit(0);
  96. default:
  97. printf("Invalid choice");
  98. }
  99. } while(loop);
  100.  
  101. getch();
  102. }
Using the stack

Although the stack is an easy data structure to implement, it is very useful. The most common uses for the stack are for the following tasks:

  • To flip a word - put all the letters in a pile and pull them out. Due to the order of the LIFO stack, you will get the letters in reverse order.
  • In compilers - compilers use the stack to calculate the value of expressions such as 2 + 4/5 * (7-9) by converting the expression to prefix or postfix form.
  • In browsers - The back button in the browser saves all the URLs you have visited previously in the stack. Each time you visit a new page, it is added to the top of the stack. When you click the back button, the current URL is removed from the stack and the previous URL is opened.

Recommended articles on this topic

By article asked0question(s)

2

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html