Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Linear Data Structures

Linear Data Structures

In this chapter, we will introduce the most basic and commonly used category of data structures —Linear Data Structures。

Linear Data StructuresIt is like a row of people standing in line:

Imagine you are lining up to buy coffee, or organizing books on a shelf.

These scenarios have one thing in common: elements are arranged one after another, forming a line.

In computer science, such an ordered collection of data is a linear data structure.

Linear data structures are characterized by: except for the first and last elements, each element has exactly one predecessor and one successor。

Common linear data structures:

  1. arrays: like a row of numbered lockers, each with a fixed position
  2. Linked list: like a chain of people holding hands, each remembering only the people before and after
  3. Stack: like a stack of plates, which can only be added or removed from the top
  4. Queue: like lining up to buy tickets, first come, first served

The figure below shows the classification of linear data structures, each with its specific application scenarios and performance characteristics:

The figure below shows the basic operations of a stack, which follows the LIFO (last in, first out) principle:

Array

Static arrays

Feature Description Time Complexity
Accessing elements Direct access by index O(1)
Insert elements Need to move the subsequent elements O(n)
Delete elements Need to move the subsequent elements O(n)
Space allocation fixed size, pre-allocated O(1)

Dynamic array

Feature Description Time Complexity
Accessing elements Direct access by index O(1)
Insert elements may need resizing and copying average O(1), worst O(n)
Delete elements Need to move the subsequent elements O(n)
Space allocation automatic resizing O(n) (during resizing)

Linked List

Singly linked list

Operation Description Time Complexity
Accessing elements requires traversal from the beginning O(n)
head insertion direct insertion O(1)
insertion at the end requires traversing to the end O(n)
insertion in the middle requires first finding the position O(n)
Delete elements requires first finding the position O(n)

Doubly linked list

Operation Description Time Complexity
Accessing elements requires traversal from the head or tail O(n)
head insertion direct insertion O(1)
insertion at the end direct insertion (if there is a tail pointer) O(1)
insertion in the middle requires first finding the position O(n)
Delete elements requires first finding the position O(n)

Stack

Operation Description Time Complexity
push (onto stack) add an element at the top of the stack O(1)
pop (off stack) remove the top element of the stack O(1)
peek (view top) View the top element of the stack O(1)
isEmpty (empty check) Check whether the stack is empty O(1)

Queue

Operation Description Time Complexity
enqueue (add to queue) Add an element at the tail O(1)
dequeue (remove from queue) Remove the front element of the queue O(1)
front (view the front) View the front element of the queue O(1)
isEmpty (empty check) Check whether the queue is empty O(1)

Linear data structures comparison diagram


Arrays: A fixed apartment building for data

An array is the simplest and most straightforward linear data structure.

We can imagine it as an apartment building with a fixed number of floors。

Basic concepts and characteristics

Core operations and code examples

Let's use Python to demonstrate arrays (usually simulated with list in Python, but note that Python's list is dynamic) core operations.

Example

1. Create an array

apartment_building

=

[

'Room 101 - Zhang San'

,

'Room 102 - Li Si'

,

'Room 103 - Wang Wu'

,

'Room 104 - Vacant'

,

'Room 105 - Vacant'

]

print

(

"Apartment building residents:"

,

apartment_building

)

2. Access elements (by index)

Access Room 102

tenant

=

apartment_building

[

1

]

Indices start at 0, so 1 corresponds to the second element

print

(

f

"The resident of Room 102 is: {tenant}"

)

3. Update an element

A new resident Zhao Liu moved into Room 104

apartment_building

[

3

]

=

'Room 104 - Zhao Liu'

print

(

"After Zhao Liu moved in:"

,

apartment_building

)

4. Insert an element (adding at the end is relatively efficient, simulating "expansion")

Suppose we allow adding a Room 106 at the end

apartment_building.

append

(

'Room 106 - Sun Qi'

)

print

(

"After adding Room 106:"

,

apartment_building

)

5. Delete an element

Wang Wu in Room 103 moved away

Method 1: Mark as vacant (logical deletion)

apartment_building[2] = 'Room 103 - Vacant'

Method 2: Remove the element, subsequent elements need to shift forward (physical deletion, less efficient)

removed_tenant

=

apartment_building.

pop

(

2

)

Remove the element at index 2

print

(

f

"{removed_tenant} has moved out."

)

print

(

"After Wang Wu moved out:"

,

apartment_building

)

Output:

寓楼住户情况: ['101室-张三', '102室-李四', '103室-王五', '104室-空置', '105室-空置']

102室的住户是:102室-李四

赵六入住后: ['101室-张三', '102室-李四', '103室-王五', '104室-赵六', '105室-空置']

加盖106室后: ['101室-张三', '102室-李四', '103室-王五', '104室-赵六', '105室-空置', '106室-孙七']

103室-王五 已搬走。

王五搬走后: ['101室-张三', '102室-李四', '104室-赵六', '105室-空置', '106室-孙七']

Advantages and Disadvantages

Advantages Disadvantages
Fast random access: Any element can be accessed in constant time through its index. fixed size: Once a static array is created, its capacity is difficult to change.
High memory efficiency: Contiguous storage, no extra space needed to store relationships between elements. High cost of insertion/deletion: Inserting or deleting elements in the middle requires moving many subsequent elements to maintain contiguity.

Linked Lists: A treasure-hunting train for data

When the fixed size of arrays and the inefficiency of insertion/deletion become problems, linked lists come into play. A linked list is like a train, where each car (node) carries cargo (data) and is connected to the next car via a hook (pointer).

Basic concepts and types

Each of a linked list's Node contains at least two parts:

  1. data field: Stores the actual data value.
  2. pointer field: Stores the address of the next node in memory.

The diagram above shows a Singly linked list structure. The head pointer points to the first node, and each node's Next pointer points to the next node, and the last node's Next Pointers to NULLpointer is NULL, indicating the end of the linked list.

Main types of linked lists:

Core operations and code examples

Let's implement a simple singly linked list.

Example

class

ListNode:

   

"""Define the linked list node class"""

   

def

init

(

self

,

data

)

:

       

self

.

data

=

data  

data field

       

self

.

next

=

None

 

pointer field, initially pointing to null

class

LinkedList:

   

"""Define the singly linked list class"""

   

def

init

(

self

)

:

       

self

.

head

=

None

 

linked list head pointer

   

def

append

(

self

,

data

)

:

       

"""Add a node to the end of the linked list"""

        new_node

=

ListNode

(

data

)

       

if

not

self

.

head

:  

If the list is empty, the new node becomes the head node

           

self

.

head

=

new_node

           

return

        last_node

=

self

.

head

       

while

last_node.

next

:  

Traverse to the last node

            last_node

=

last_node.

next

        last_node.

next

=

new_node  

Attach the new node to the end

   

def

prepend

(

self

,

data

)

:

       

"""Add a node to the head of the linked list"""

        new_node

=

ListNode

(

data

)

        new_node.

next

=

self

.

head

       

self

.

head

=

new_node

   

def

delete

(

self

,

key

)

:

       

"""Delete the first node whose value is key"""

        current_node

=

self

.

head

       

If the node to delete is the head node

       

if

current_node

and

current_node.

data

==

key:

           

self

.

head

=

current_node.

next

            current_node

=

None

           

return

        prev_node

=

None

       

Traverse to find the node to delete

       

while

current_node

and

current_node.

data

!=

key:

            prev_node

=

current_node

            current_node

=

current_node.

next

       

if

current_node

is

None

:  

Not found

           

return

       

Once found, bypass the node and reconnect

        prev_node.

next

=

current_node.

next

        current_node

=

None

   

def

print_list

(

self

)

:

       

"""Print all elements of the linked list"""

        current_node

=

self

.

head

       

while

current_node:

           

print

(

current_node.

data

,

end

=

" -> "

)

            current_node

=

current_node.

next

       

print

(

"NULL"

)

Test the linked list

print

(

"=== Singly linked list operation demo ==="

)

train

=

LinkedList

(

)

train.

append

(

"Car 1 - Coal"

)

train.

append

(

"Car 2 - Timber"

)

train.

prepend

(

"Locomotive"

)

 

Add at the head

train.

append

(

"Car 3 - Steel"

)

print

(

"Initial train:"

)

train.

print_list

(

)

 

Output: Locomotive -> Car 1 - Coal -> Car 2 - Timber -> Car 3 - Steel -> NULL

train.

delete

(

"Car 2 - Timber"

)

print

(

"After unloading the timber:"

)

train.

print_list

(

)

 

Output: Locomotive -> Car 1 - Coal -> Car 3 - Steel -> NULL

Output:

=== 单向链表操作演示 ===

Initial train:

车头 -> 车厢1-煤炭 -> 车厢2-木材 -> 车厢3-钢材 -> NULL

After unloading the wood:

车头 -> 车厢1-煤炭 -> 车厢3-钢材 -> NULL

Advantages and Disadvantages

Advantages Disadvantages
Dynamic size: No need to pre-allocate fixed space; can grow and shrink flexibly. Memory overhead: Each node needs extra space to store pointers.
Efficient insertion/deletion: When the node position is known, only pointers need to be modified, without moving many elements. Sequential access: Cannot be accessed directly by index like an array; must be traversed from the head.
Cache-unfriendly: Nodes are scattered in memory, which is unfavorable for CPU cache prefetching.

Stacks: A stack of plates for data

A stack is a last-in-first-out data structure, like plates stacked in a restaurant, where you always take the top one (the last one placed).

Basic concepts and operations

A stack only allows insertion ( stack top) at one end (called thepush) and deletion (pop) there. The other end is called the stack bottom。

Core operations:

Application scenarios and code examples

Stacks are widely used in computer science, for example: function call stacks, browser forward/back navigation, expression evaluation, bracket matching, and so on.

Example

class

Stack:

   

"""Implement a stack using a list"""

   

def

init

(

self

)

:

       

self

.

items

=

[

]

   

def

push

(

self

,

item

)

:

       

"""Push onto the stack"""

       

self

.

items

.

append

(

item

)

 

Use the end of the list as the top of the stack

   

def

pop

(

self

)

:

       

"""Pop from the stack, return None if empty"""

       

if

not

self

.

is_empty

(

)

:

           

return

self

.

items

.

pop

(

)

       

return

None

   

def

peek

(

self

)

:

       

"""View the top element of the stack"""

       

if

not

self

.

is_empty

(

)

:

           

return

self

.

items

[

1

]

       

return

None

   

def

is_empty

(

self

)

:

       

"""Check whether the stack is empty"""

       

return

len

(

self

.

items

)

==

0

   

def

size

(

self

)

:

       

"""Return the size of the stack"""

       

return

len

(

self

.

items

)

Application example: Bracket matching check

def

is_balanced_parentheses

(

expression

)

:

   

"""
    Check whether brackets in an expression are balanced
    For example: (()) is balanced, (() is not
    """

    stack

=

Stack

(

)

   

bracket matching map

    matching_bracket

=

{

')'

:

'('

,

']'

:

'['

,

'}'

:

'{'

}

   

for

char

in

expression:

       

if

char

in

'([{'

:  

If it's a left bracket, push it onto the stack

            stack.

push

(

char

)

       

elif

char

in

')]}'

:  

If it's a right bracket

           

if

stack.

is_empty

(

)

:

               

return

False

 

The stack is empty, meaning there are too many right brackets

            top_char

=

stack.

pop

(

)

           

if

matching_bracket

[

char

]

!=

top_char:  

Check whether it matches

               

return

False

   

After the loop, the stack should be empty

   

return

stack.

is_empty

(

)

Test the stack and bracket matching

print

(

"\n=== Stack and bracket matching demo ==="

)

plate_stack

=

Stack

(

)

plate_stack.

push

(

"Plate 1"

)

plate_stack.

push

(

"Plate 2"

)

plate_stack.

push

(

"Plate 3"

)

print

(

f

"Take the top plate: {plate_stack.pop()}"

)

 

Output: Plate 3

print

(

f

"The top plate is now: {plate_stack.peek()}"

)

 

Output: Plate 2

Test bracket matching

test_cases

=

[

"((1+2)*3)"

,

"({[ ]})"

,

"((())"

,

")( )"

]

for

test

in

test_cases:

    result

=

"Balanced"

if

is_balanced_parentheses

(

test

)

else

"Unbalanced"

   

print

(

f

"The brackets in expression '{test}' are {result}."

)

Output:

=== 栈与括号匹配演示 ===

取出最上面的盘子: 盘子3

现在最上面的盘子是: 盘子2

表达式 '((1+2)*3)' 的括号是 平衡 的。

表达式 '({[ ]})' 的括号是 平衡 的。

表达式 '((())' 的括号是 不平衡 的。

表达式 ')( )' 的括号是 不平衡 的。


Queues: A waiting line for data

A queue is a First In First Out data structure, like any place in life where you need to line up (such as a supermarket checkout), where the first to arrive is served first.

Basic concepts and operations

A queue allows insertion at one end (called the Rear) at one end (called theenqueue) operation, and deletion at the other end (called the queue front) (Dequeue) operation.

Core operations:

Application scenarios and code examples

Queues are often used in scenarios requiring tasks to be processed in order, such as: print job queues, message queues, breadth-first search, and so on.

Example

from

collections

import

deque  

Use Python's deque, which provides efficient operations at both the head and tail

class

Queue

:

   

"""Implement a queue using collections.deque"""

   

def

init

(

self

)

:

       

self

.

items

=

deque

(

)

   

def

enqueue

(

self

,

item

)

:

       

"""Enqueue"""

       

self

.

items

.

append

(

item

)

 

Add from the right side (the rear)

   

def

dequeue

(

self

)

:

       

"""Dequeue, return None if the queue is empty"""

       

if

not

self

.

is_empty

(

)

:

           

return

self

.

items

.

popleft

(

)

 

Remove from the left side (the front)

       

return

None

   

def

front

(

self

)

:

       

"""View the front element"""

       

if

not

self

.

is_empty

(

)

:

           

return

self

.

items

[

0

]

       

return

None

   

def

is_empty

(

self

)

:

       

"""Check whether the queue is empty"""

       

return

len

(

self

.

items

)

==

0

   

def

size

(

self

)

:

       

"""Return the size of the queue"""

       

return

len

(

self

.

items

)

Application example: Simulating print jobs

print

(

"\n=== Queue and print job simulation ==="

)

printer_queue

=

Queue

(

)

Simulate the arrival of three print jobs

tasks

=

[

"Alice's resume.pdf"

,

"Bob's report.doc"

,

"Charlie's chart.png"

]

for

task

in

tasks:

    printer_queue.

enqueue

(

task

)

   

print

(

f

"Task '{task}' has been added to the print queue."

)

Process print jobs

print

(

"\nStarting to print..."

)

while

not

printer_queue.

is_empty

(

)

:

    current_task

=

printer_queue.

dequeue

(

)

   

print

(

f

"Printing: {current_task}"

)

   

Simulate printing time

print

(

"All print jobs are complete."

)

Output:

=== 队列与打印任务模拟 ===

任务 'Alice的简历.pdf' 已加入打印队列。

任务 'Bob的报告.doc' 已加入打印队列。

任务 'Charlie的图表.png' 已加入打印队列。



开始打印...

正在打印: Alice的简历.pdf

正在打印: Bob的报告.doc

正在打印: Charlie的图表.png

所有打印任务已完成。


Summary and comparison

We have learned four fundamental linear data structures. The table below helps you quickly review and compare their core characteristics:

Feature arrays Linked list Stack Queue
Storage method Contiguous memory Scattered memory, connected via pointers Implemented based on arrays or linked lists Implemented based on arrays or linked lists
Access Method Random access (by index) Sequential access (must traverse) Only the top of the stack (LIFO) Only the front of the queue (FIFO)
Insertion/deletion efficiency Fast at the tail, slow in the middle/at the head (requires moving elements) Fast when the position is known (only pointers change) Stack-top operations, O(1) Enqueue at the rear, dequeue at the front, O(1)
Size Fixed (static array) Dynamic Dynamic Dynamic
Main applications Fast lookup, fixed collections Frequent insertions/deletions, uncertain size Function calls, backtracking, bracket matching Task scheduling, buffering, BFS

How to choose?