DSA Lab 8
DSA Lab 8
DSA Lab 8
_________________________________________________________
SIGNATURE & DATE
___________________________________________________________________
NATIONAL UNIVERSITY OF COMPUTER AND EMERGING SCIENCE
(NUCES) KARACHI
OBJECTIVES:
A linked list is a linear data structure, in which the elements are not stored at
contiguous memory locations. The elements in a linked list are linked using pointers as
shown in the below image:
In simple words, a linked list consists of nodes where each node contains a data
field and a reference (link) to the next node in the list.
What is a Node?
A linked list usually consists of a root node, allocated on the stack and one or more
nodes allocated on the heap (by calling new). Each node is a structure object. The data
filed holds the information stored in the node. The next field saves address of the next
node in the linked list. The end of the linked list is indicated by setting the next field to
NULL, which means that there is no node next to this node. Nodes are allocated on the
heap memory using new operator.
This is what a single linked list looks like diagrammatically. Each node has a
Key/Value which are strings in the case shown above, and a reference i.e., a next
pointer that points to the next element. Basically, the first node is the head, and the last
node is the tail in the list. The movement from one node to other is called traversal in
the list.
Head and tail of a linked list:
A singly linked list is also a collection of nodes and has a starting point called as
HEAD and an endpoint called TAIL.
Head is the pointer that simply points or identifies to the first element in the
singly linked list.
Tail identifies to the last node in the singly linked list and in this case, the
reference part of the node points to nothing or nil.
NOTE:A singly linked list does not have a predetermined size, so it uses
spaceproportionally according to the number of elements present in the list and unlike
arrays, it does not have the contiguous memory allocation i.e., they are not allocated one
after another, rather, distributed in memory and attached through pointer that we call the
reference part.
The size of the arrays is fixed: So, we must know the upper limit on the number
of elements in advance. Also, generally, the allocated memory is equal to the upper
limit irrespective of the usage.
And if we want to insert a new ID 1005, then to maintain the sorted order, we
must move all the elements after 1000 (excluding 1000).
Deletion is also expensive with arrays until unless some special techniques are
used. For example, to delete 1010 in id [ ], everything after 1010 has to be moved.
1. Dynamic size
2. Ease of insertion/deletion
Drawbacks:
2. Extra memory space for a pointer is required with each element of the list.
3. Not cache friendly. Since array elements are contiguous locations, there is
locality of reference which is not there in case of linked lists.
Each link carries a data field(s) and a link field called next.
Each link is linked with its next link using its next link.
Last link carries a link as null to mark the end of the list.
1. Data
In python, LinkedList can be represented as a class and a Node as a separate class. The
LinkedList class contains a reference of Node class type.
# Node class
class Node:
def __init__(self,data):
# Function to initialise the node object
self.data = data # Assign data
self.next = None # Initialize next as null
------------------------------------------------------------------
class LinkedList:
def __init__(self): #Function to initialize the Linked List
self.head = None
def printList(self):
temp = self.head
while (temp):
print (temp.data,end=' , ')
temp = temp.next
------------------------------------------------------------------
# Code execution starts here
if __name__=='__main__':
The new node is always added before the head of the given Linked List. And
newly added node becomes the new head of the Linked List.
We add an item 5 at the front, then the Linked List becomes 5->10->15->20-
>25.
Let us call the function that adds at the front of the list is insert_beginning ().
We are given pointer to a node, and the new node is inserted after the given node.
the new node is always added after the last node of the given Linked List.
For example:
1. If the given Linked List is 5->10->15->20->25
2. We add an item 30 at the end, then the Linked List becomes 5->10->15->20-
>25>30.
3. Since a Linked List is typically represented by the head of it, we have to
traverse the list till end and then change the next of last node to new node.
Time complexity of append is O(n) where n is the number of nodes in linked list. Since
there is a loop from head to end, the function does O(n) work. This method can also be
optimized to work in O(1) by keeping an extra pointer to tail of linked list/
We can delete a node from anywhere in a linked list. The delete method traverses the list
in the same way that search does, but in addition to keeping track of the current node, the
delete method also remembers the last node it visited. When delete finally arrives at the
node it wants to delete, it simply removes that node from the chain by “leap frogging” it.
By this I mean that when the delete method reaches the node it wants to delete, it looks at
the last node it visited (the ‘previous’ node), and resets that previous node’s pointer so that,
rather than pointing to the soon-to-be-deleted node, it will point to the next node in line.
Since no nodes are pointing to the poor node that is being deleted, it is effectively removed
from the list!
The time complexity for delete is also O(n), because in the worst case it will visit every
node, interacting with each node a fixed number of times.
Search:
Search is actually very similar to size, but instead of traversing the whole list of
nodes it checks at each stop to see whether the current node has the requested data and if
so, returns the node holding that data. If the method goes through the entire list but still
hasn’t found the data, it raises a value error and notifies the user that the data is not in the
list.
Once a linked list is created, we can search for a particular item in it. We start from
the root node and keep moving to the next node unless either we find the desired item, or
the linked list ends i.e., node is NULL. In the former case, search is successful i.e., the
item is found, whereas in the latter case search is unsuccessful. The time complexity of
search is O(n) in the worst case (you often hear about best case / average case / worst case
for Big O analysis. For this purpose of this blog post, we’ll assume worst case is the one
we care about it, because it often
is!)
Lab Report:
(It is recommended to write Lab Report in bullet Form)
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
print("4.Delete at beginning")
print("5.Delete at middle")
print("6.Delete at end")
print("7.Traversal Forward")
print("8.Count number of nodes")
print("9.Exit")
ch=int(input("Enter your choice [1-8]: "))
if ch==1:
x=int(input("enter the value"))
a.insert_beginning(x)
a.printlist()
elif ch==2:
x=int(input("enter the value"))
a.insert_middle(1,x)
a.printlist()
elif ch==3:
x=int(input("enter the value"))
a.insert_end(x)
a.printlist()
elif ch==4:
a.delete_beginning()
a.printlist()
elif ch==5:
x=int(input("enter the value"))
a.delete_middle(x)
a.printlist()
elif ch==6:
a.delete_end()
a.printlist()
elif ch==7:
a.traverse_forward()
a.printlist()
elif ch==8:
a.count_nodes()
a.printlist()