0% found this document useful (0 votes)
11 views

BASU S Learn Data Structure Array Linked List Stack Queue Using Python in 5 Minutes 2021

Uploaded by

gatodaprata
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

BASU S Learn Data Structure Array Linked List Stack Queue Using Python in 5 Minutes 2021

Uploaded by

gatodaprata
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

LEARN

DATA STRUCTURE
LINKED LIST
ARRAY
STACK
QUEUE
USING
PYTHON
IN 5 MINUTES
Copyright © 2021 S Basu
All rights reserved.
Disclaimer:
The information and materials presented here are for educational
purposes only. Every effort has been made to make this book as
complete and as accurate as possible but no warranty or fitness is
implied. The information provided is on an "as is" basis. The ideas and
opinions expressed are of the author's own imagination and the author is
not affiliated to any organization, school or educational discipline and
will not be held accountable or liable for any inadvertent
misrepresentation.
Contents
Chapter 1 : Few Important Python Basics
1.1 : What is a Python module?
1.2 : What is a Python function?
1.3 : What is a Python class?
Chapter 2 : Array
Chapter 3 : Linked List
3.1 : Creating a Linked List & displaying its values
3.2 : Insert a node in the beginning of the Linked List
3.3 : Insert a node in the middle of the Linked List
3.4 : Insert a node at the end of the Linked List
3.5 : Deletion
3.6 : Types of Linked List
3.7 : Difference between a Array and a Linked List
Chapter 4 : Stack
Chapter 5 : Queue
Chapter 1 : Few Important Python
Basics
Before we start learning about data structure related topics like linked list,
array, stack and queue, we first need to get an understanding about a few
python basics like how to create a python module, run a python code and
what is a python function or a python class.
So let us first review these python topics.

1.1 : What is a Python module?


Python module is a Python file that contains functions, classes, and
variables that group a logical functionality together.

Modules can be imported for use in code.

Let’s create a simple Python file or module,

Open Notepad++ and create a new file (hello_world ) and save the
file with .py extension

Inside hello_world.py file, write one line of code:


What is print( ) function in Python?

print( ) function displays the output to the screen

Now let’s run the above piece of code.


Open command prompt -> Go to the hello_world.py file location and type
the following command:
python file_name .py

The output displays


Now let’s create another Python file and name it test.py

In test.py file, simply import the hello_world module created above.


Now run this file.
Open command prompt -> Go to the test.py file location and write the
following command:
python test .py

We see that the test module prints out “Hello World ” output from
hello_world module.

What is import statement in Python?

import statement in Python allows a Python file or module to access all


the codes present in another Python file or module.

1.2 : What is a Python function?


Python Functions are just like Java methods. It is a block of codes
performing certain task.

Syntax:
def function_name ( ) :
……..

Example:

Code Explanation:

In the above piece of code, we created a function


validate_username with parameter uname. If the argument is
“John123 ”, the function prints “Hello John ” or else it will print
“Wrong username ”.

To call any function, we simply have to write the function name


followed by parenthesis . Within that parenthesis, we passed the
value of username which is “John123 ”
Output

Difference between parameter and argument

Parameter is the variable passed to a function . Example:

function function_name ( variable1 , variable2 ) :


Argument is the value assigned to the variables. Example:

function_name ( 123,”Hello_World” )

1.3 : What is a Python class?


● Python is an object oriented programming language .
● A class is a “blueprint” for creating an object and like any other
programming language Python class contains attributes and methods.

● Python object contains the copy of all attributes and methods present
within its class. To access those properties dot operator ( . ) is used.
The syntax for creating a class is:

class class_name :
def __init__(self) :
….
def method1 :
….
The syntax for creating an object of a class is:
class Hello :
def __init__(self) :
………………
…………
h = Hello( ) , where h is the object of class Hello .

What is def __init__ (self)?

"__init__" is a reserved method in Python classes initializing the object


’s state. In Object Oriented concepts, it refers to the constructor of the
class . This method initializes the attributes of a class when an object is
created.
self keyword helps to access the attributes of the class.

Example:

Output

Important points to note from the above piece of code are:

1. A Python Class name should start with a capital letter.

2. Within the __init__method we declared different attributes of our


class Employee and passed those values to self . id_num , self .
name and so on.
3. In our validation ( ) method we pass the argument self which helps
to access all the attributes of the class Employee .

4. str( ) function helps to convert an integer value to a string value.

5. and keyword is the logical and operator in Python.

6. In line 15 of the above code, we created an object e and passed


values into it.
Chapter 2 : Array
An Array is a collection of items or elements all having the same datatypes.
An element from an array can only be accessed from its index value.
Example: Let’s create an array of cars.

cars = [“Kia”, “Toyota”, “Ford”, “Tesla”]

In order to get the value Ford as output, we need to write print ( cars [ 2 ]
)

In Python, a List is very similar to an Array . It contains a list of


elements separated by commas and its elements are written with
square brackets [ …. ] .

A value from a List can be accessed from its index value and the
syntax is.

List_name [ index_num ]

Example:
Create a new Python file (variables.py ) and write the following lines of
code:
After running the above piece of code, we get an output of:

Code explanation:
● In the above piece of code, fruits is a List containing 6 elements. The
value at position 0 is “apple ”, at position 1 is “orange ” and so on.

● x is a variable holding a string value. The value at position 0 is “t” , at


position 1 is “h ” and so on.
● len( ) function is used to get the length of the list .

● In Line 4 and 5 we are performing Slicing operation .


print ( fruits [ 2 : 4] ) means print elements from position 2
(including its value ) to position 4 (excluding its value ).

Output: [‘banana’, ‘mango’]


print ( x [ 2 : 8 ] ) means print the values of x (“this apple is
tasty ”) from position 2 (including its value ) to position 8
(excluding its value ).
Output: is app

NOTE : To insert a data into an array list, python provides us with insert
method.

The syntax is:

array_list . insert ( index_value , data_element )

To delete an element from the array list, python provide us with remove
method.

The syntax is:

array_list . remove ( data_element )

Now let’s run the above piece of code:


Chapter 3 : Linked List
A Linked List is a Linear Data Structure which is a collection of
data elements or nodes .

Each node contains a data and an address or pointer which points


to the next node .

The first node is called the Head and the last node is called the Tail.
The last node always points to NULL.

What is data structure?


Data structure is the process of organizing and storing the data.
It is classified into two types:
1. Linear Data Structure – In this type of data structure, the data
elements are arranged in a linear sequential order, but it is not compulsory
to store the elements sequentially. Example: Array, Linked List, Stacks &
Queue.
2. Non-Linear Data Structure – In this type of data structure, the data
elements are arranged in a non-linear order. Example: Tree and graphs.

Let's code..
3.1 : Creating a Linked List & displaying its values

Open Notepad++ and create a new python file and name it linked_list.py
and write the following lines of code.

In the above piece of code, we simply created the Node class which
contains two attributes, one is value or data of the linked list node and the
other one is the next pointer which points to the next node of the linked
list.
For now the next pointer points to none.
Now let's create the Linked List class
The Linked_List class contains only one attribute head and for now the
head is empty or none .
The image below shows the order in which we will create our linked list.

Head = n1
n1.next = n2
n2.next = n3
n3 points to none or null
Code explanation:

In line 8, we created object s of class Linked_List( ).

In line 9, we created the first node of the linked list using Node
class and assigned that node to head .
s.head now act as an object of class Node

In line 10, we created the second node of the linked list.

In line 11, we created the third node of the linked list.

In line 12, we linked the second node and the third node using next
attribute of class Node .

In line 13, we link the head with the second node .

From line 14 to line 16, using while loop , we display the values of
each node of the linked list.

Now let's save everything and run the python module.

To run the above piece of code,


Open command prompt -> navigate to the python file location and run
using python command as shown in the screen shot below.

3.2 : Insert a node in the beginning of the Linked List

Let us suppose we want to assign a node x as the new head of the linked
list as shown in the image below.
In order to do this the following three steps are needed:
Step 1 : Move the existing linked list (suppose linked list z ) and store it in
a temporary variable.

Step 2 : Create a new node and assign that node to the head .

Step 3 : Now link the new head with the existing linked list z with the help
of next pointer.

In linked_list.py , add the following function in class Linked_List .

Now let's call the newly created function .


Run the above piece of code.

Time Complexity : Since we know in which position we need to add the


new node , so no iteration is required, hence the time complexity is O(1)

What is Time Complexity and Big-O notation?

Time complexity denotes the amount of time taken by the code to execute.

The Big-O notation is the growth rate of a function . It usually provides the upper limit on the
growth rate of an algorithm or function .

3.3 : Insert a node in the middle of the Linked List


Suppose we want to insert a new node x after node y in the linked list as
shown in the image below.

In order to do this the following two steps are needed:


Step 1: Node y was previously pointing to node a . The y node ’s next must
be removed and assigned to x node ’s next making node x point to node a .

Step 2: y node ’s next must point to node x .

In linked_list.py , add the following function in class Linked_List .

Now let's call the newly created function .


Run the above piece of code.

Time Complexity : In this case we have a reference node and know the
position in which we are inserting the new node , so the time complexity
is O(1).
If we do not have a reference node and have to iterate through the linked
list to insert a node , in that case the time complexity is O(n) , where n
refers to the input size. For example, in a list , n refers to the number of
elements.

3.4 : Insert a node at the end of the Linked List

Suppose we want to insert node b at the end of the linked list as shown in
the image below.

In order to do this the following two steps are needed:


Step 1: We need to loop through the pointers and reach the end of the
linked list. Once the pointer next points to none , then stop the loop and
return the last node a of the linked list.

Step 2: Now make the last node a of the linked list point to the new node
b
In linked_list.py , add the following function in class Linked_List .
Now let's call the newly created function .

Run the above piece of code.


Time Complexity : Since we are traversing the linked list to add a new
node, the time complexity is O(n)

3.5 : Deletion

Suppose we want to remove node b from the linked list as shown in the
image below.

In order to do this the following two steps are needed:


Step 1: Replace the b node ’s value with next node 's (node c ) value.

Step 2: Make the b node ’s next attribute point to c node ’s next attribute
which is pointing to node d

In linked_list.py , add the following function in class Linked_List .


Now let's call the newly created function .

Run the above piece of code.


Time Complexity : Since no iteration is performed to find the node, the
time complexity is O(1)

3.6 : Types of Linked List

A linked list is of three types:


1. Singly Linked List - A singly linked list is generally a linked list
in which each node contains a data and a pointer next which
points to the next node .

2. Doubly Linked List - In doubly linked list, each node contains


data and two pointers next and prev . Pointer next points to the
next node and pointer prev points to the previous node .

While coding, we just need to add one extra attribute prev to the class
Node
Head = n1
n1.next = n2
n2.prev = n1
n2.next points to none or null
n1.prev points to none or null
The highlighted piece of code in the screen shot above shows the double
linked list insert function .
Code explanation:

In line 10, we created a new node new_node .

In line 11, we made the new_node point to head with the help of
next attribute.

In line 12, we check whether there is a head node present or not.

➢ If head node is present, then make the head node point to the new
node with the help of prev attribute.

Then in line self.head = new_node , make the new_node as the new


head node .

3. Circular Linked List - A circular linked list is like a singly linked


list except for the fact that the last node does not point to NULL.
The last node of the circular linked list points to the head node .

In the above image,


head = n1
n1.next = n2
n2.next = n3
n3.next = n1

In the code below we will create a circular linked list and will display the
values.
Code explanation:
In the above piece of code we created our general linked list, but we
made the last node (n3 ) point to the head of the linked list in line:

n3.next = s.head

While displaying the values from the linked list,

In line current = s.head , we assigned the head node (suppose n1


) to a variable current .

In line print(current.value), we print the value of n1 . (It will


print 5 )

In line while(current.next != s.head):, we perform a while loop .

➢ current.next of n1 is n2 which is not equal to the n1 , so the


condition returns true. The value of n2 is printed.
➢ Then again current.next of n2 is n3 and n3 is not equal to n1
, so the condition returns true. The value of n3 is printed.
➢ Then again current.next of n3 is n1 and n1 is indeed equal to
n1 , so the condition returns false and the while loop stops.

Now let’s run the above piece of code

How to know a Linked List is circular or not?

In order to check whether a linked list is circular or not, we need to perform


two steps:
Step 1: Get the last node of the linked list.

Step 2: Check whether the last node points to the head node . If last node
points to the head node , then it is a circular linked list.

In the highlighted piece of code above, we check whether the last node
points to head or not.

Now run the above piece of code.

3.7 : Difference between a Array and a Linked List


Array Linked List
An array is a collection of data
elements having a fixed size. It is Linked List is dynamic in nature.
static in nature
In Array, accessing an element is
faster. It helps us to access any In Linked List, we need to perform
elements simply from its index iteration to access any element.
value. Hence the time complexity Hence the time complexity is O(n)
is O(1)
In Linked list memory is allocated
during runtime (Dynamic memory
In an Array, memory is allocated allocation). Memory consumption is
during compile time (Static also more in linked lists compared
memory allocation). to arrays and this is because each
node contains data and a pointer
which requires extra memory.
Chapter 4 : Stack
A stack is a data structure which is used for storing data element. For
example: Let us consider that in a kitchen cabinet, plates a, b, c, d are
stacked one on the another as shown in the image below.

Plate a is the first one to go in and plate d is the last one to enter the cabinet.
When we want to use a plate, we usually take plate d and it is the first plate
to be removed and plate a is the last one to be removed.
This concept is similar to a data structure stack . The first data element
inserted into the stack (plate a in the above example ) is the last one to be
removed and the last element inserted into the stack (plate d of above
example ) is the first one to be removed. Hence stack is called Last In
First Out (LIFO) or First In Last Out (FILO) list. The insertion and
deletion always occurs from one end and that is the top .
NOTE: The data elements are pushed and popped from the top of the
stack which has a special index value of -1. When the stack is empty the
index value of top is -1.
The operation of adding and removing the elements is called PUSH
and POP respectively. Python provide us with append( ) and pop( )
functions to add and remove the data elements.

Now create a new python file and name it stack.py and write the following
lines of code.
Code explanation:

Stack class is declared and it contains only one attribute stack


which is empty for now.

push function appends or adds a data element into the stack.

pop function pops or removes the last data element entered from
the top of the stack .

peek function returns the top value of the stack.

Run the above piece of code.


Time Complexity : push and pop operation is done from one end and no
iteration is performed, so the time complexity is O(1)
Chapter 5 : Queue
Queue is a data structure which stores data elements. In this data elements
are inserted from one end (rear ) and deletion is performed from the other
end (front ). For example: Let us consider a drive-through car wash line.

The first car which enters the line gets washed first and they leave. Then the
second car is washed and then the third car. Similarly in queue , the first
data element inserted gets removed first and the last data element inserted
gets removed last. Hence queue is called First in First Out (FIFO) or
Last In Last Out (LILO) list .
When an element is inserted into the queue , the concept is called
EnQueue and when an element is removed from the queue , the concept is
called DeQueue .

Now create a new python file and name it queue.py and write the following
lines of code.
Code explanation:

Function enqueue adds new values into the queue .

Funtion dequeue removes the first values inserted into the


queue.
Run the above piece of code.

Time Complexity : No iteration was performed in enqueue and dequeue


operation, so the time complexity is O(1)
Wish you all the best and thank you very much for
buying this book.

Always remember, the most important learning is


Self-Learning..

You might also like