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

Week 04 - Linked Lists - 1

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)
40 views

Week 04 - Linked Lists - 1

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/ 44

CS 250

Data Structures & Algorithms


(Week 04: Linked List - I)
Dr. Muhammad Kamran Khan
Assistant Professor

Department of Electrical Engineering


Military College of Signals
National University of Sciences and Technology (NUST)

1
Definition-List
• A list is a collection of items that has a
particular order
– It can have an arbitrary length
– Objects / elements can be inserted or
removed at arbitrary locations in the list
– A list can be traversed in order one item at a
time

2
LINKED LISTS

3
Linked List
 Linked List is a linear data structure, in which elements
are not stored at a contiguous location, rather they are
linked using pointers.
 Linked List forms a series of connected nodes, where each
node stores the data and the address of the next node.

4
Linked Lists Terminologies
 Traversal of List
 Means to visit every element or node in the list
beginning from first to last.

 Predecessor and Successor


 In the list of elements, for any location n, (n-1) is
predecessor and (n+1) is successor.
 In other words, for any location n in the list, the left
element is predecessor and the right element is
successor.
 Also, the first element does not have predecessor and
the last element does not have successor.

5
Linked List

A B C 

Head

 A linked list is a series of connected nodes


 Each node contains at least :
 A piece of data (any type)
 Pointer to the next node in the list
node
 Head: pointer to the first node
A
 The last node points to NULL
data pointer

6
Linked Lists

7
Introduction to Linked Lists
Arrays vs. Linked lists
Arrays Linked Lists
Arrays are stored in contiguous Not stored in contiguous
location. location
Fixed in size Dynamic in size
Memory is located at compile Memory is allocated at run
time time
Use less memory than linked Uses more memory because it
lists store both data and address
Elements can be easily Elements accessing requires
accessed traversal of whole linked list
Insertion and deletion operation Insertion and deletion operation
takes time is faster

9
Array versus Linked Lists
• Linked lists are more complex to code and manage
than arrays, but they have some distinct advantages.
– Dynamic: a linked list can easily grow and shrink in size.
• We don’t need to know how many nodes will be in the list. They
are created in memory as needed.
• In contrast, the size of an array is fixed at compilation time.
– Easy and fast insertions and deletions
• To insert or delete an element in an array, we need to copy to
temporary variables to make room for new elements or close the
gap caused by deleted elements.
• With a linked list, no need to move other nodes. Only need to
reset some pointers.
Array vs. Linked List

An Array Linked List

11
Types of Linked Lists
 There are mainly three types of linked lists:
1. Single-linked list
2. Double linked list
3. Circular linked list

12
Single-Linked List
 In a singly linked list, each node contains a reference to
the next node in the sequence. Traversing a singly linked
list is done in a forward direction.

13
An Integer Linked List

First Node of List Last Node of List


list
10 13 5 2

data next NULL

14
Creating a Node
# Node class
class Node:
def __init__(self, data): # Function to initialize the node object
self.data = data # Assign data
self.next = None # Initialize next as null

# Linked List class


class LinkedList:
# Function to initialize the Linked List object
def __init__(self):
self.head = None

15
Operations on Linked List
 Insertion: Adding a new node to a linked list involves adjusting the
pointers of the existing nodes to maintain the proper sequence.
Insertion can be performed at the beginning, end, or any position
within the list
 Deletion: Removing a node from a linked list requires adjusting the
pointers of the neighboring nodes to bridge the gap left by the
deleted node. Deletion can be performed at the beginning, end, or
any position within the list.
 Searching: Searching for a specific value in a linked list involves
traversing the list from the head node until the value is found or the
end of the list is reached.
 Display : This process displays the elements of a Single-linked list.

16
Insertion
 Insertion:
1. At the beginning of the list
2. At the end of the list
3. At the specific location in the list

 Deletion:
1. from the beginning of the list
2. from the end of the list
3. a specific node

 Searching: Searching for a specific value in a linked list involves


traversing the list from the head node until the value is found or the end of
the list is reached.
 Display : This process displays the elements of a Single-linked list.

17
Insertion (at the beginning of the list)
 To insert a node at the start/beginning of a Linked List, we need to:
1. Make the first node of Linked List linked to the new node
2. Remove the head from the original first node of Linked List
3. Make the new node as the Head of the Linked List.

18
Insertion (at the beginning of the list)
# This function is in LinkedList class
# Function to insert a new node at the beginning
def push(self, new_data):
# 1 & 2: Allocate the Node & Put in the data
new_node = Node(new_data)

# 3. Make next of new Node as head


new_node.next = self.head

# 4. Move the head to point to new Node


self.head = new_node

19
Display Function
def display_list(self):
if self.IsEmpty()==True:
print(“list is empty”)
return
temp=self.head
while temp!=None:
print(temp.data)
temp=temp.next

20
Traversal
temp=head
temp contains the reference 500
head and prints the data
temp
temp=temp.next
30 2000 temp temp contains the reference 2000
500 and prints the data
20 1000 temp temp=temp.next
2000

10 None
temp contains the reference
1000
1000 and prints the data

temp=temp.next

temp temp=temp.next
temp contains None
and exits the loop
Display nodes having odd data

def display_odd(self):
temp=self.head
while temp!=None:
if temp.data%2 != 0:
print(temp.data)
temp=temp.next

22
Display alternate nodes
def display_alter(self):
temp=self.head
while temp!=None:
print(temp.data)
temp=temp.next
if temp==None:
break
temp=temp.next

23
Nodeappend(self,d)
 Means insert as a last node
 No reference for the last node, so need to traverse the list
till the last node

24
Nodeappend(self,d)
def append(self,d):
temp=self.head
temp2=Node(50)
if self.IsEmpty()==True:
self.head=temp2
return

while(temp.next!=None):
temp=temp.next

temp.next=temp2

25
Traversal

temp=head
head temp temp contains the reference 500
temp=temp.next
30 2000 temp temp contains the reference 2000
500
temp=temp.next
20 1000 temp
2000

10 None
temp=temp.next
1550
1000
temp contains the reference
1000
temp2=Node(50)
temp2
50 None
temp.next=temp2 1550
Traversal

head

30 2000
500
20 1000
2000

10 1550
1000

50 None
1550
count_nodes(self)
def count_nodes(self):
temp=Node()
temp=self.head
c=0
while(temp!=None):
c=c+1
temp=temp.next
return c

28
sum_data()
def sum_data(self):
temp=Node()
temp=self.head
c=0
while(temp!=None):
c=c+temp.data
temp=temp.next
return c

29
Insert-in-between
 Insert a node in between the two nodes
 Two temporary node type variables are required
 A new node is to be created
 Links are to be updated
 The method takes 2 arguments
- Position at which the new node is to be inserted
- Data for the new node

30
Required Steps
 Validate the given position
 Assume the two Nodes P and Q
P Q

 And a new Node n


n

 The requirement is to insert ‘n’ in between ‘P’ and


‘Q’

31
Required Steps
n

P Q

1. Create a link between n and Q (n.next=P.next)


2. Update the link of P by changing its next (P.next=n)
Final Shape

P Q
Advantages of Linked List
• Dynamic Data structure: The size of memory can be allocated or
de-allocated at run time based on the operation insertion or deletion.

• Ease of Insertion/Deletion: The insertion and deletion of elements


are simpler than arrays since no elements need to be shifted after
insertion and deletion, Just the address needed to be updated.

• Efficient Memory Utilization: As we know Linked List is a


dynamic data structure the size increases or decreases as per the
requirement so this avoids the wastage of memory.

 Flexibility: Linked lists can be easily reorganized and modified


without requiring a contiguous block of memory.

34
Disadvantages of Linked List
 Random Access: Unlike arrays, linked lists do not allow direct
access to elements by index. Traversal is required to reach a specific
node.
 Extra Memory: Linked lists require additional memory for storing
the pointers, compared to arrays.

35
Doubly Linked List

36
Introduction
• The singly linked list contains only one pointer
field i.e. every node holds an address of next node.

• The singly linked list is uni-directional i.e. we can


only move from one node to its successor.

• This limitation can be overcome by Doubly linked


list.

37
Limitations of Singly Linked List
 Can only access the next element
 Cannot traverse in reverse in easier manner

38
Doubly Linked List
 In a doubly linked list, each node contains references to
both the next and previous nodes.
 This allows for traversal in both forward and backward
directions (bi-directional), but it requires additional
memory for the backward reference.

39
Doubly Linked List

Prev Data Next

head tail

None A 2000 1000 B 3000 2000 C None


1000 2000 3000

40
Advantages of Doubly Linked List
1. The doubly linked list is bi-directional, i.e. it can
be traversed in both backward and forward
direction.

2. The operations such as insertion, deletion and


searching can become easier.

3. Predecessor and successor of any element can be


searched quickly

41
Disadvantages of Doubly Linked List
1. It consume more memory space.

2. There is a large pointer adjustment during


insertion and deletion of element.
3. It consumes more time for few basic list
operations.

42
Circular-Linked List
 In a circular linked list, the last node points back to the
head node, creating a circular structure. It can be either
singly or doubly linked.

43
THANK YOU

44

You might also like