Implementing Linked Lists, Queue & Stack in Python

Sathu
4 min readJun 7, 2019

As important it is to store data, depending on the use case it is crucial to organize and manage it efficiently. The dynamic properties of the above data structures let us use these for various applications. Be it the Tower of Hanoi algorithm, Palindrome recognition, Making a music playlist they come in handy during logical scenarios. This article aims to provide the implementation of the data structures in Python programming.

High-level data structures, Stacks and Queues are basically array-like. The core difference between them is the sequence in which the data is inserted and eliminated. Coming to Linked Lists, these are linear structures consisting of nodes and dependencies among each other. Let's dig deeper one at a time.

Linked Lists

Like in the game Treasure hunt, you find the first clue, use the information from that and find the second clue and the message there leads you to the third. Similarly, Linked Lists is a series of connected “nodes” that contains the “address” of the next node. Each node can store a data point.

Data Structure — Linked Lists

Implementing the above logic in code:

Implementing Linked Lists in Python

Inserting elements to a Linked list at its tail is just creating another node and connecting the previous node to the newly created element. Let's say we are unsure of the number of nodes we have and need to insert an element at the tail. When all we have is a head node then the code is as below.

Inserting node in a Linked List (Tail)

Similarly deleting a node:

Deleting node in a Linked List

Queue

Queue is an open-ended data structure. One end is always used to insert data (enqueue) and the other is used to eliminate data (dequeue). This adapts FIFO (First In First Out) methodology i.e the item stored first is used first. Consider it as cola sucked through a straw, the liquid that enters the straw first enters your mouth first, as simple as that.

Thanks to the container module collections in python, we can initialize a queue by giving the size.

Implementing a Queue in Python

Set a size for the queue and insert data into it. It is important to mind the order of the data inserted given it’s FIFO methodology.

Inserting data in the Queue
Removing element from the queue

Stack

A stack is an ordered list in which, insertion and deletion can be performed only at one end that is called top. Stacks are sometimes called as Last-In-First-Out (LIFO) lists i.e. the element which is inserted first in the stack, will be deleted last from the stack.

Let's see how the basic push, pop operations can be implemented in a stack using append and pop functions.

Implementing a Stack in Python

Assign a variable to stack object and insert data into it.

Removing element from Stack

It’s fascinating to how simple implementations as above form crucial entities in various problem-solving approaches. Happy Coding!!

--

--