2. • What are the limitations of an array, as a data structure?
– Fixed size
– Physically stored in consecutive memory locations
– To insert or delete items, may need to shift data
• Linked list provides two advantages over arrays
- Dynamic size
- Ease of insertion/deletion
Limitations of arrays
3. • A linked data structure consists of items that are linked to other items
– How? each item points to another item
• Singly linked list: each item points to the next item
• Doubly linked list: each item points to the next item and to the previous item
• Circular linked list: a singly linked list where the last item holds the address of the first item
Linked data structures
4.
5. • A linked list is an ordered sequence of items called nodes
– A node is the basic unit of representation in a linked list
• A node in a singly linked list consists of two fields:
– A data portion
– A link (pointer) to the next node in the structure
• The first item (node) in the linked list is accessed via a front or head pointer
– The linked list is defined by its head (this is its starting point)
data link
Node
6. •Creating a list
•Traversing the list
•Inserting an item in the list
•Deleting an item from the list
•Concatenating two lists into one
Basic operations on a single linked list
7. # Node class
class Node:
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class
class LinkedList:
def __init__(self):
self.start = None
data None
None
data next
self.start
newnode
Creation of a node
8. def createlist(self):
n=int(input("enter number of node")) #say n=3
for i in range(n):
data=int(input("enter value"))
newnode=Node(data)
if self.start==None:
self.start=newnode
else:
temp=self.start
while temp.next!=None:
temp=temp.next
temp.next=newnode
Single linked list – Algorithm
10. 21 3000 22 None
2000 3000
2000
self.start
21 3000 22 4000
2000 3000
2000
self.start
23 None
4000
CASE 2: insertion of a node at tail
temp
temp newnode
11. We will now examine linked list operations:
• Add an item to the linked list
– We have 3 situations to consider:
• insert a node at the front
• insert a node after a given node.
• insert a node at the end
• Delete an item from the linked list
– We have 3 situations to consider:
• delete the node at the front
• delete an interior node
• delete the last node
Operations on a single linked list