Linked Lists in
Python
WMSU
What is a Linked List?
• A linked list is a sequence of
data elements, which are
connected together via
links.
• Each data element contains
a connection to another
data element in form of a
pointer.
Why Linked List?
Arrays can be used to store linear data of similar types, but arrays have
the following limitations.
1) The size of the arrays is fixed
2) Inserting a new element in an array of elements is expensive
For example, in a system, if we maintain a sorted list of IDs in an array id[].
id[] = [1000, 1010, 1050, 2000, 2040]
1005
Why Linked List?
Arrays can be used to store linear data of similar types, but arrays have
the following limitations.
1) The size of the arrays is fixed
2) Inserting a new element in an array of elements is expensive
For example, in a system, if we maintain a sorted list of IDs in an array id[].
id[] = [1000, 1005, 1010, 1050, 2000, 2040]
Representation:
Angel 1010
data pointer
[Link] second third
1 NONE 2 NONE 3 NONE
[Link] second third
1 2 NONE 3 NONE
[Link] second third
1 2 3 NONE
Output:
1→2→3
Python
Output:
1
2
3
INSERTING A NODE
A node can be added in 3 ways:
1. At the front of the linked list.
2. After a given node.
3. At the end of the linked list.
Adding node at the front
10 15 20 25
5 10 15 20 25
Adding node after a given node
Adding node at the end:
push() Output:
1
append() 2
insertAfter() pushh 3
Output:
1
2
3
4
Output:
0
1
2
3
4
Output:
-1
0
1
2
3
4
Output:
-1
0
1
2
3
4
5
Output:
-1
0
1
2
2.5
3
4
5
DELETING A NODE
To delete a node from the linked list, we need to
do the following steps.
1) Find the previous node of the node to be deleted.
2) Change the next of the previous node.
3) Free memory for the node to be deleted.
Deleting a node:
Output:
-1
0
1
2
2.5
3
3
4
4
5
5
Activity:
1. Code the entire Python program that was shown earlier.
Printscreen the code and the output.
2. Add another line of code that will append 3 numbers, append 3
characters, push 3 strings. Printscreen the additional code and the
output.
3. Add another line of code that will delete any number, character,
and string. Printscreen the additional code and its output.
Attach all your printscreen in the Google Classroom activity that
I will post.
Thank you and God bless