Types of Data Structures: Linear, Non-Linear and How to Choose One

What each type of data structure stores, how fast its operations run, which one to choose, and what C, C++, Java, Python and C# provide.

Blue array cells and linked grey beads on the left, a branching tree and a small network of nodes on the right.

The same million integers took 4,199,056 bytes of heap in a circular array and 32,000,000 bytes in a linked list when the queue tutorial measured them. Nothing about the data changed. The structure did, and with it the memory, the speed of every operation and the bugs a program is likely to have.

This guide is the map for the data structures on MYCPLUS. It defines what a data structure is, sorts the common types into linear, hash-based and non-linear structures, gives the time complexity of each in one table, and shows which type to reach for in a given situation. It closes with the containers that C, C++, Java, Python and C# already provide. Each structure links to a tutorial that builds it with working code, so this page stays short on code and long on comparison.

What Is a Data Structure?

A data structure is a way of organizing data in memory so that the operations a program needs, such as finding, adding and removing items, run efficiently.

The definition in NIST’s Dictionary of Algorithms and Data Structures is close to that: an organization of information, usually in memory, for better algorithm efficiency. The important word is efficiency. Every structure makes some operations cheap and others expensive, and choosing one means choosing which operations the program will do most.

Two ideas are easy to confuse. An abstract data type describes behaviour: a stack promises last in, first out, and says nothing about memory. A data structure is a concrete layout that delivers the behaviour: an array with a top index, or a linked list whose head is the top. The stack tutorial builds both layouts and measures the difference. Most of this page is about layouts, because the layout decides the cost.

Data structures are built from primitive types, the integers, floating-point numbers, characters and booleans a language provides directly. Some textbooks call those primitive data structures and everything built from them non-primitive. This guide covers the non-primitive structures, since those are the ones a programmer designs and chooses.

Types of data structuresData structuresLinearArrayDynamic arrayLinked listStackQueue and dequeHash-basedHash tableHash setNon-linearTree and BSTBalanced tree, B-treeHeapTrieGraph
Figure 1: The three groups used in this guide. Linear structures keep a sequence, hash-based structures find items by key, and non-linear structures model hierarchy and connection.

Linear and Non-Linear Data Structures

The most common way to classify data structures is by how the elements relate to each other.

GroupHow elements relateExamplesTypical question it answers
LinearEach element has at most one predecessor and one successor, so the elements form a sequenceArray, dynamic array, linked list, stack, queue, dequeWhat comes next, first or last?
Hash-basedElements are placed by a hash of their key, with no meaningful orderHash table, hash setIs this key present, and what is its value?
Non-linearAn element can connect to several othersTree, binary search tree, heap, trie, graphWhat is below, above or connected to this item?

Hash tables are a special case. They are stored in an array, but the order of that array means nothing, so some textbooks list them as linear, some as non-linear and some, like this guide, as a group of their own. The classification matters less than the behaviour: a hash table answers lookups by key and cannot answer questions about order.

A second classification is static versus dynamic. A static structure has a size fixed when it is created, like a C array declared as int scores[100]. A dynamic structure grows and shrinks while the program runs, like a linked list or a std::vector. Static structures cost nothing to manage and cannot overflow their memory budget, while dynamic structures adapt to the input at the price of allocation. The arrays tutorial covers both kinds of array in C and C++.

Linear Data Structures

Array

An array stores elements of one type next to each other in memory, so the address of element i is the start address plus i times the element size. That arithmetic is why reading any element by index takes constant time, and why arrays are the fastest structure to scan from start to end: the processor’s cache loads neighbouring elements together. The cost is that inserting or deleting in the middle shifts every later element.

Dynamic Array

A dynamic array is an array that reallocates itself when it fills, usually doubling its capacity and copying the elements across. The copies are rare enough that adding at the end costs constant time on average, which is called amortized constant time. C++’s std::vector, Java’s ArrayList, Python’s list and C#’s List<T> are all dynamic arrays. The std::vector guide shows the growth from the C++ side.

Linked List

A linked list stores each element in a separate node that points to the next node, and in a doubly linked list to the previous one as well. Inserting or removing next to a node you already hold is constant time, and the nodes never move in memory. The price is that reaching the i-th element means walking i links, and every node costs an allocation and at least one pointer. The linked list tutorial builds one in C.

Stack

A stack allows access at one end only: push adds an item on top and pop removes the most recent one, last in, first out. Function calls, undo histories, expression parsing and depth-first search all use stacks. An array or a linked list can back it, and both give constant-time push and pop, as the stack tutorial shows in five languages.

Queue and Deque

A queue adds at the back and removes from the front, first in, first out, which is the order of print jobs, event loops, network buffers and breadth-first search. A deque, or double-ended queue, allows both operations at both ends. A circular array is the usual layout for both, and the queue tutorial explains why a circular array needs a count or a spare slot to tell a full queue from an empty one.

Hash Tables

A hash table stores key and value pairs in an array of buckets. A hash function turns each key into a bucket index, so finding a key means computing its hash and looking in one bucket instead of searching the whole collection. On average, lookup, insertion and deletion take constant time, as long as the hash spreads the keys evenly and the table grows before it gets too full.

Two keys can land in the same bucket. Separate chaining keeps a short list in each bucket, while open addressing probes forward to the next free slot. The hash table tutorial builds both in five languages and measures how probe lengths grow with the load factor. A hash table is unordered, so it cannot list keys in sorted order or answer range queries. Combined with a linked list, it becomes the classic cache, as in the LRU and FIFO cache simulator.

Trees

A tree is a hierarchy: one root node, and every other node has exactly one parent and any number of children. Trees model anything nested, such as file systems, HTML documents, organization charts and the syntax of a program. The binary trees tutorial covers the structure and its traversals.

Binary Search Tree

A binary search tree keeps smaller keys in the left subtree and larger keys in the right, so a search discards half of the remaining tree at each step when the tree is balanced. Unlike a hash table, it also returns keys in sorted order and answers range queries. Its weakness is shape: keys inserted in sorted order produce a tree that is really a linked list, and every operation degrades to linear time.

Balanced Trees and B-Trees

Balanced trees such as AVL trees and red-black trees rebalance themselves after each change, which guarantees logarithmic time whatever the insertion order. They are the structure behind ordered maps: Java’s TreeMap, which Oracle’s documentation lists as a balanced tree, and in practice C++’s std::map. A B-tree stores many keys per node, so a lookup touches few nodes, which is why databases and file systems use it for data on disk.

Heap

A binary heap is a tree stored in an array, in which every parent is smaller than its children (a min-heap) or larger (a max-heap). The smallest or largest item is always at the root, so a heap is the usual way to build a priority queue: schedulers, Dijkstra’s shortest-path algorithm and event simulations all take the most urgent item next. The heap sort article shows the array layout in detail.

Trie

A trie stores strings character by character along its paths, so all words with a common prefix share the same branch. Looking up a word takes time proportional to its length, not to the number of words stored, which makes tries the structure behind autocomplete and spell checking. The trie tutorial implements one in C++.

Graphs

A graph is a set of vertices connected by edges, with no root and no restriction on how many connections a vertex has. Road networks, social networks, the links between web pages and the dependencies between build targets are all graphs. Edges can have a direction and a weight, such as a one-way street and its length.

A program stores a graph in one of two ways. An adjacency matrix is a V by V table with a cell for every possible edge, which answers “is there an edge from u to v?” in constant time but uses V squared cells even when the graph has few edges. An adjacency list keeps, for each vertex, a list of its neighbours, which uses space proportional to V plus E and suits the sparse graphs most real problems produce.

Shortest paths and minimum spanning trees are graph algorithms, covered in the shortest path and Kruskal’s algorithm articles. A specialised graph, the binary decision diagram, represents Boolean functions compactly.

Time Complexity of Common Data Structures

The table gives the cost of the four basic operations in Big-O notation, where n is the number of elements. Average and worst cases are shown separately where they differ.

StructureAccess by positionSearch for a valueInsertDelete
ArrayO(1)O(n), or O(log n) with binary search if sortedO(n)O(n)
Dynamic arrayO(1)O(n)O(1) amortized at the end, O(n) elsewhereO(1) at the end, O(n) elsewhere
Singly linked listO(n)O(n)O(1) at the head or after a known nodeO(1) at the head, O(n) elsewhere
Doubly linked listO(n)O(n)O(1) at either end or next to a known nodeO(1) for a known node
StackTop only, O(1)O(n)O(1) pushO(1) pop
QueueFront only, O(1)O(n)O(1) enqueueO(1) dequeue
Hash tableNot supportedO(1) average, O(n) worstO(1) average, O(n) worstO(1) average, O(n) worst
Binary search treeNot supportedO(log n) average, O(n) worstO(log n) average, O(n) worstO(log n) average, O(n) worst
Balanced tree (AVL, red-black, B-tree)Not supportedO(log n)O(log n)O(log n)
Binary heapMinimum or maximum only, O(1)O(n)O(log n)O(log n) for the root
Trie (key length m)Not supportedO(m)O(m)O(m)

Three notes keep the table honest. The binary search tree’s average assumes keys arrive in random order, and sorted input gives the worst case. The hash table’s average assumes a good hash and a bounded load factor, and an attacker who chooses colliding keys can force the worst case. Big-O ignores constants, so a simpler structure can win on small inputs: in the linear search article, a plain scan of a sorted array beat binary search up to 128 elements on the test machine.

Space matters as well. Arrays and dynamic arrays use one slot per element plus any spare capacity. Linked lists, trees and node-based hash tables add one or more pointers per element and an allocation each, which is how the linked queue in the opening example used more than seven times the memory of the circular array.

Which Data Structure Should I Use?

Start from the operation the program performs most often, then pick the structure that makes it cheapest.

If the program mostly needs toUseWhy
Read items by position and append at the endDynamic arrayConstant-time indexing and amortized constant appends, with the best cache behaviour
Undo, backtrack or match nested bracketsStackThe most recent item is always the next one needed
Process items in arrival orderQueueFirst in, first out at constant cost
Add and remove at both endsDequeConstant time at either end
Insert and remove in the middle while holding a referenceLinked listNo elements move, so references stay valid
Look up values by keyHash tableConstant time on average, if order does not matter
Keep keys sorted, or find all keys in a rangeBalanced search treeLogarithmic operations and in-order traversal
Always take the smallest or largest item nextHeap (priority queue)The root holds it, and insert and remove are logarithmic
Search by prefix, such as autocompleteTrieCost depends on the key length, not on the number of keys
Model connections, routes or dependenciesGraphVertices and edges represent the relationships directly

When two structures fit, prefer the simpler one and measure. A dynamic array is the right default far more often than its textbook complexity suggests, because contiguous memory is fast and most collections are small.

Data Structures in C, C++, Java, Python and C#

Most languages ship the common structures in their standard library, and production code should use them unless it needs control over the layout. C is the exception: the ISO C library has no containers, only qsort and bsearch for arrays, so C programs build their own or use a library. POSIX systems add hsearch and tsearch in <search.h>, but they are limited and not part of standard C.

StructureCC++JavaPythonC#
Dynamic arrayWrite one with reallocstd::vectorArrayListlistList<T>
Linked listWrite onestd::list, std::forward_listLinkedListNone built inLinkedList<T>
StackWrite onestd::stackArrayDequelist with append and popStack<T>
Queue and dequeWrite onestd::queue, std::dequeArrayDequecollections.dequeQueue<T>
Priority queueWrite onestd::priority_queue (max-heap)PriorityQueue (min-heap)heapq (min-heap)PriorityQueue<TElement,TPriority> (min)
Hash mapWrite onestd::unordered_mapHashMapdictDictionary<TKey,TValue>
Hash setWrite onestd::unordered_setHashSetsetHashSet<T>
Ordered mapWrite onestd::mapTreeMapNone built inSortedDictionary<TKey,TValue>

The official references list the full sets: C++ containers on cppreference, the Java Collections Framework overview, data structures in the Python tutorial and collections and data structures in .NET. For C++, the STL containers guide explains which container to pick and when.

Two differences catch people moving between languages. C++’s std::priority_queue puts the largest item on top, while Java’s PriorityQueue, Python’s heapq and .NET’s PriorityQueue return the smallest first. In Java, the old Stack class still exists, but its own documentation recommends the Deque interface, usually ArrayDeque, instead.

Key Takeaways

  • A data structure is a memory layout chosen to make a program’s most frequent operations cheap, and every choice makes some other operation expensive.
  • Linear structures (arrays, lists, stacks, queues) keep a sequence, hash tables find items by key, and non-linear structures (trees, heaps, graphs) model hierarchy and connection.
  • Arrays give constant-time indexing and the best cache behaviour, while linked lists give constant-time insertion next to a known node at the cost of a pointer and an allocation per element.
  • Hash tables average constant-time lookup but keep no order, while balanced trees keep keys sorted at logarithmic cost.
  • Heaps serve priority queues, tries serve prefix search, and graphs model networks of any shape.
  • C has no standard containers. C++, Java, Python and C# ship most of these structures, and production code should use them.

Frequently Asked Questions

Conclusion

Pick a data structure by the operation your program performs most, not by the one you know best. Use a dynamic array by default, a hash table when lookups by key dominate, a balanced tree when you need sorted order or ranges, and a heap when you always need the most urgent item next. Use your language’s standard container unless you have measured a reason not to. Each structure on this page has its own tutorial with working code in the data structures category, starting with arrays and linked lists.

Scroll to Top