Stack
In the previous topic, we implemented a stack structure based on arrays. However, with such a structure, we encounter the need to dynamically resize the array by allocating new memory for it or, conversely, reducing it. An alternative is to create a stack based on a singly linked list. The singly linked list structure is simple, yet quite efficient for creating other data structures.
Each element in the stack, as in a singly linked list, will be represented by a Node class:
1 2 3 4 5 6 7 8 9 | public class Node<T> |
Based on the Node class, we can implement a stack structure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | using System;using System.Collections.Generic; using System.Collections;
public int Count
public T Pop() Node<T> temp = head; return temp.Data; public T Peek() return head. Data;
|
Unlike the previous stack implementation, which relied on arrays, here we overcome the limitations of arrays—we don’t need to recreate the array when adding or removing data. We simply reset the reference to the head element, which is the top of the stack. The algorithmic complexity of both Push and Pop is O(1) .
Thus, we have obtained a relatively simple and quite effective solution.
Stack usage:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | using System;using System.Collections; using System.Collections.Generic;
string header = stack.Peek();
|
Console output:
Kate Bob Alice Tom Top of the stack: Kate Bob Alice Tom
Explore More IT Terms
A
B
C
D
E
F
H
K
W
- What are databases, and why do they need DBMS and SQL?
- What do Linux distributions consist of?
- What is a GPU in a computer, in simple terms?
- What is Linux? The History of Linux
- What is the OSI Model: A Complete Explanation of the Seven Layers and Their Role in Networking
- Which Linux distribution should you choose? A Linux distribution overview
