Singly Linked Lists: CS235-Data Structures
Singly Linked Lists: CS235-Data Structures
Singly Linked Lists: CS235-Data Structures
CS235-Data structures
Both array-based sequences and linked lists keep elements in a
certain order, but using a very different style.
3
Singly Linked Lists
Singly Linked Lists
Definition
A singly linked list, in its simplest form, is a collection of nodes that
collectively form a linear sequence. Each node stores a reference to
an object that is an element of the sequence, as well as a reference
to the next node of the list
4
Singly Linked Lists
Definition : traverse
By starting at the head, and moving from one node to another by
following each node’s next reference, we can reach the tail of the
list. We can identify the tail as the node having None as its next
reference. This process is commonly known as traversing the linked
list.
5
Singly Linked Lists
6
Creating a linked list
• class Node():
• def __init__(self, data):
• self.data = data
• a = Node(10)
• b = Node(20)
• a.next = b
• b.next = None
• print(a.data)
• print(a.next.data)
Singly Linked Lists
Inserting an Element at the Head of a Singly
Linked List
Inserting an Element at the Head of a Singly Linked
List
How to insert an element at the head of the
list?
9
Inserting an Element at the Head of a Singly
Linked List
10
Inserting an Element at the Head of a Singly Linked
List
INSERT_AT_BEGINNING(L, n)
n.next = L.head
L.head = n
11
Singly Linked Lists
Inserting an Element at the tail of a Singly Linked
List
Inserting an Element at the tail of a Singly
Linked List
We can also easily insert an element at the tail of the list, provided
we keep a reference to the tail node.
12
Inserting an Element at the tail of a Singly Linked
List
INSERT_AT_LAST(L, n)
temp = L.head
while(temp.next != null)
temp = temp.next
temp.next = n
13
Singly Linked Lists
Inserting an Element at random position of a Singly
Linked List
Inserting an Element at random position of a
Singly Linked List
We can also easily insert an element at the tail of the list, provided
we keep a reference to the tail node.
12
Inserting an Element at random position of a Singly
Linked List
INSERT_NODE_AFTER(n, a)
n.next = a.next
a.next = n
13
Singly Linked Lists
Removing an Element of a Singly Linked List
Removing an Element at the head of a Singly
Linked List
14
Removing an Element at the head of a Singly
Linked List
Removing an element from the head of a singly linked list is
essentially the reverse operation of inserting a new element at the
head.
14
Removing an Element at the tail of a Singly
Linked List
15
Removing an Element at random position of
a Singly Linked List
15