Linked List 1 -with out code
Linked List 1 -with out code
1 2 3 4
Lecture Flow
● Pre-requisites
● Definition and Introduction
● Types of Linked Lists
● Arrays vs Linked Lists
● Common Operations on Linked Lists
● Practice Questions
Pre-requisites
1. Arrays
2. Pointers
De nitions
Linked List is a linear data structure that stores value and
grows dynamically
5
Linked List consists of nodes where each node contains a
data field and a reference(link) to the next node in the list
1 2 3 4
6
Node
● stores the value and the reference to the next node.
● The simplest linked list example
class Node:
self.value = value
7
Types of Linked List
Singly Linked List is when nodes have only next’s node
reference.
1 2 3 4
Doubly Linked List is when nodes have both previous and
next node reference.
1 2 3 4
Why do we need linked
list when we have
arrays?
11
Why Linked List when you have Arrays?
12
Arrays vs Linked List
Array Linked List
Insertions and Deletions are inefficient Insertions and Deletions are efficient
14
Traversing a Linked List
● Start with the head of the list. Access the content of the head node
if it is not null
● Go to the next node(if exists) and access the node information
● Continue until no more nodes (that is, you have reached the last
node)
15
Problem
Write a function that returns an array representation of a given linked
list.
a = Node(1)
b = Node(2) [1, 2, 3]
c = Node(3)
a.next = b
b.next = c
16
Inserting a node in linked list
18
Insert at the beginning
● If list is empty
○ make new node the head of the list
● Otherwise
○ connect new node to the current head
○ make new node the head of the list.
19
Insert at any position
● Find the insert position and the previous node
● And then make the next of new node as the next of previous node
● Finally, make the next of the previous node the new node
21
22
Can we merge the two insertions into one
function?
How?
24
Yes, we can use Dummy Node before the
head.
25
Dummy Node
26
Delete a node from the linked list
27
Delete a node at the beginning
28
Delete a node at any position
30
31
Can we avoid using two approaches when
we are deleting nodes? How?
33
Yes again! We can use Dummy Node.
34
Checkpoint - Link
problem
Remove Linked List Element
36
Linked List Class
● The LinkedList class serves as the container for the nodes.
● The __init__ method initializes an empty linked list with a head pointing to
None.
class LinkedList:
def __init__(self):
self.head = None
37
Pair Programming
Design Linked List(implement deleteAtIndex)
38
Resources
● Leetcode Explore Card: has excellent track path with good explanations
● Leetcode Solution (Find the Duplicate Number) : has good explanation
about Floyd’s cycle detection algorithm with good simulation
● Elements of Programming Interview book: has a very good Linked List
Problems set
39
40