You are on page 1of 38

DATA STRUCTURES

DESIGN
Unit – 2
Linear Structures- List
LIST ADT
List is a linear collection of data items. The general form of list is,

A1, A2, A3, . . . AN

Where, N is the size of the list. A1 is the first element of the list. AN is the last element of the list. The list of 0
elements is called as empty list. For any list, the element at position i is A i, then Ai+1 follows (succeeds) Ai and Ai-1
precedes Ai.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Operations Performed on the list

Insert (X, P) – Insert the element X after the position P. Next (i) – Returns the position of successor element i + 1.

Previous (i) – Returns the position of its predecessor element


Example: Insert (X, 4):
i – 1.
36, 23, 49, 53, 12, 98 will be 36, 23, 49, 53, X, 12, 98
Print List – Print the elements of the list.
Delete (X) – Delete the element X from the list.
Make Empty – Make the list empty.

Example: Delete (12):

36, 23, 49, 53, X, 12, 98 will be 36, 23, 49, 53, X, 98

Find (X) – Returns the position of X.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Implementation of List ADT

List can be implemented in two ways. They are,

1. Array based implementation


2. Linked list implementation

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
ARRAY BASED IMPLEMENTATION
 The simplest way of representing a list is using an array.
 In an array-based implementation of list, a group of related variables can be stored one after
another in a continuous memory location.
 The entire contents of an array are identified by a single name. Individual elements within the
array can be accessed directly by specifying an integer subscript or index value.
 Python's list structure is a mutable sequence container that can change its size when items are
added or removed. It is an abstract data type that is implemented using an array structure to
store the items contained in the list.

• Example: 4,12,2,34,17 can be represented as,

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Creating a Python List
 When the list() constructor is called, an array structure is created to store the items in the list.
 The array is initially created bigger than needed, leaving capacity for future expansion. The values stored in
the list comprise a subarray in which only a contiguous subset of the array elements is actually used.

 The elements with null references shown outside the dashed grey box are the remaining elements of the array
structure that are still available for future use.
 The length of the list, obtained using len(), is the number of items currently in the subarray and not the size of
the underlying array. The size or capacity of the array is used to know when the array is full.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Appending Items
• The append() method is used to insert the item to the end of the list. If there is a room in the
array, the item is stored in the next available slot of the array and the length field is incremented
by one.
 An array cannot change its size once it has been created. When the array becomes full and there
is no free slot to append the item, the list allows expansion of list. It can be performed by,
1. A new array is created with additional capacity,
2. The items from the original array are copied to the new array,
3. The new larger array is set as the data structure for the list, and
4. The original smaller array is destroyed.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
To insert 6, the array will have to be expanded to make 3. The new array replaces the original in the list.
room for value 6.
1. A new array, double the size of the original, is created.

4. Value 6 is appended to the end of the list.


2. The values from the original array are copied to the new
larger array.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Insertion
• Insertion is the process of adding an element into the existing list. It can be done at any position.
 Insertion at position ‘0’ requires, pushing the entire array down one position to make a room for the new
element.
 An item can be inserted anywhere within the list using the insert() method.

Example:
• To insert 79 at index 3
• The insert(3,79) method insert the value 79 at index position 3. Since there is already an item at that position, we
must make room for the new item by shifting all of the items down one position starting with the item at index
position 3.
 After shifting the items, the value 79 is then inserted at position 3. If there are no free slots for the new item, the
list will be expanded.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Routine:
def insert(self, k, value):
if self. n == self. capacity:
self. resize(2 self. capacity)
for j in range(self. n, k, −1): # shift rightmost first
self. A[j] = self. A[j−1]
self. A[k] = value # store newest element
self. n += 1

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Deletion

• Deletion is the process of removing an element from the array at any position.
 Python’s list class offers several ways to remove an element from a list. A call to pop( ) removes
the last element from a list. This is most efficient, because all other elements remain in their
original location. This is effectively an O(1) operation.
 pop(k), removes the element that is at index k in a list, shifting all subsequent elements leftward
to fill the gap that results from the removal. The efficiency of this operation is O(n−k), as the
amount of shifting depends upon the choice of index k.
 pop(0) is the most expensive call, using Ω(n) time.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Routine:
def remove(self, value):
for k in range(self. n):
if self. A[k] == value:
for j in range(k, self. n − 1):
self. A[j] = self. A[j+1]
self. A[self. n − 1] = None
self. n −= 1
return
raise ValueError( value not found )

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
LINKED LIST IMPLEMENTATION

• In linked list implementation of list, the linked list consists of series of nodes, which are not
necessarily adjacent in memory.
Data/
• Each structure consists of two parts i.e., the element and a pointer to the next node. Element
Next pointers

• The pointer is called as the next pointer. The last cells Next pointer points to NULL. The pointer
variable contains the address where some other data are stored.
• The general form of linked list is,

Representation of linked list with actual values

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
• There are three types of linked list.

1. Singly linked list


2. Doubly linked list
3. Circular linked list.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
SINGLY LINKED LIST

• A singly linked list, is a collection of nodes that collectively form a linear sequence they are not necessarily
adjacent in the memory. Each node stores an element and a reference to the next node of the list.
Elemen Pointer to the
• Structure of a node is, t next node
• The first and last node of a linked list are known as the head and tail of the list. The tail node having None/ NULL
as its next reference.
• By starting at the head, and moving from one node to another by following each node’s next reference, until reach
the tail of the list. This process is commonly known as traversing the linked list.
• An important property of a linked list is that it does not have a predetermined fixed size; it uses space
proportionally to its current number of elements.
• The general form of linked list is,

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Actual Representation

Operations performed in linked list are,


1. Insertion
2. Deletion
3. Print List (L), Find (L, Key)

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Insertion

a) Inserting an Element at the Head of a Singly Linked List

• To insert an element at the head of the list,


i) Create a new node, set its element to the new element,
ii) Set its next link to refer to the current head, and
iii) Set the list’s head to point to the new node.

Algorithm add_first(L,e):
newnode = Node(e)
newnode.next = L.head
L.head = newnode
L.size = L.size+1

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
b) Inserting an Element at the Tail of a Singly Linked List

• To insert an element at the tail of the list,


i) Create a new node, set its element to the new element assign its next reference to NULL
ii) Set the next reference of the tail to point to this new node, and
iii) Update the tail reference itself to this new node.

Algorithm add_last(L,e):
newnode = Node(e)
newnode.next = None
L.tail.next = newnode
L.tail = newnode
L.size = L.size+1

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
c) Inserting an Element at the middle of a Singly Linked List

• To insert an element at the middle of the list, first traverse the position to be inserted. Let the
previous node as ‘p’.
i) Create a new node, set its element to the new element
ii) Set the next reference of the newnode as next field of previous node, and
iii) Set the next field of previous node as newnode.

Algorithm add_mid(L,e):
newnode = Node(e)
p=FindPrevious(e,L)
newnode.next = p.next
p.next = newnode
L.size = L.size+1

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Deletion

a) Removing First Element from 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.

Algorithm remove_first(L):
if L.head is None then
Indicate an error: the list is empty.
L.head = L.head.next
L.size = L.size−1

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
b) Removing Last Element from a Singly Linked List

• To delete the last node from the list, find the node before the last node. Then make the node as
tail node and make its next reference as NULL.
Algorithm remove_last(L):
if L.tail is None then
Indicate an error: the list is empty.
p=L
while(p.next.next is not None)
p=p.next
L.tail=p
p.next = None
L.size = L.size-1

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
c) Removing Intermediate Element from a Singly Linked List

• To delete the intermediate node from the list, find the node before the node to be deleted. Then
make the following changes.

Algorithm remove_byvalue (L,e):


if L.tail is None then
print(“List is Empty”)
p=L
while(p.next is not None && p.next.data is not e)
p=p.next
p.next=p.next.next
L.size = L.size-1

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
CIRCULARLY LINKED LIST
• Circular linked list is a linked list in which the last node of the list points to the first node of the
list thus the nodes form a continuous circle.

• The circular linked list allows for a complete traversal of the nodes starting with any node in the
list.
Implementing a Queue with a Circularly Linked List
The only two instance variables are tail, which is a reference to the tail node and size, which is the
current number of elements in the queue. The self. tail. next refers the head of the queue.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Enqueue

• When enqueue is called, a new node is placed just after the tail but before the current head, and
then the new node becomes the tail.

def enqueue(self, e):


newnode = self. Node(e, None)
if self.is empty( ):
newnode. next = newnode
else:
newnode. next = self. tail. next
self. tail. next = newnode
self. tail = newnode
self. size += 1

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Dequeue
• When dequeue is called, it removes and return the first element of the queue, by, bypassing the
head node.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Applications
• It is used for applications in which data is processed in a round-robin fashion. For example, CPU
scheduling.

Advantages
• It allows traversing the list starting at any position.
 It allows quick access to the first and last nodes.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
DOUBLY LINKED LIST

• A doubly linked list is a linked list in which each node keeps an explicit reference to the node before it and a reference
to the node after it. The “next” pointer points to the next node and the “prev” pointer points to the previous node.

Header and Trailer Sentinels

In order to avoid some special cases when operating near the boundaries of a doubly
linked list, a special header node is added at the beginning of the list, and a trailer node is added at the end of the list.
These “dummy” nodes are known as sentinels (or guards), and they do not store elements of the primary sequence.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Advantage of Using Sentinels
• Using sentinel nodes in a doubly linked list treat all insertions in a unified manner. That is, a
new node will always be placed between a pair of existing nodes. Similarly, a node to be deleted
is guaranteed that has neighbours on each side.

Insertion
• Every insertion into a doubly linked list representation will take place between a pair of existing
nodes. For example, when a new element is inserted at the front of the sequence, add the new
node between the header and the node that is currently after the header.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Insertion at First
• Adding an element to the front of a sequence represented by a doubly linked list with header and
trailer sentinels. a) before the operations, b) after creating the new node, c) after linking the
neighbours to the new node.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Insertion at middle
Adding an element to a doubly linked list with header and trailer sentinels. a) before the operations, b) after
creating the new node, c) after linking the neighbours to the new node.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Deletion

• To delete a node, the two neighbours of the node to be deleted are linked directly to each other, thereby
bypassing the original node. As a result, that node will no longer be considered part of the list.

Removing the element from a doubly linked list. A) before the removal, b) After linking out the old
node, c) after the removal

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Implementation of a Doubly Linked List

class _DoublyLinkedBase: def _ _ init_ _ (self):


self._header = self._Node(None, None,
None)
class _Node:
self._trailer = self._Node(None, None,
None)
slots = _element , _prev , _next
self._header._next = self._trailer
def _ _ init_ _ (self, element, prev, next):
self._trailer._prev = self._header
self._element = element
self._size = 0
self._prev = prev
self._next = next

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
def _len_ (self): return newest
return self._size def _delete_node(self, node):
predecessor = node._prev
def is_empty(self): successor = node._next
return self._size == 0 predecessor._next = successor
successor._prev = predecessor
def _insert_between(self, e, predecessor, self._size −= 1
successor):
element = node._element
newest = self._Node(e, predecessor,
node._prev = node._next = node._element =
successor)
None
predecessor._next = newest
return element
successor._prev = newest
self._size += 1

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
APPLICATIONS OF LISTS

• There are three applications that use linked list.


1. Keep track of course registration at a university. (Multi list)
2. Polynomial manipulation.
3. Sorting method in linear time – Radix sort

• Multilist
• A university with 40,000 students and 2500 courses needs to be able to generate two types of
reports.
1. Report lists the registration for each class
2. Report list by student, the classes that each student is registered for

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
If this method uses a two-dimensional array, it would have 100 million
entries. The average student registers for about three courses have 1,20,000
entries or roughly 0.1 percent have meaningful data.
This can be implemented by a circular linked list.

To list all of the classes in class C4, we start at C3 and traverse its list. The
first cell belongs to student S1 and finds another cell that belongs to S3, S4 and
so on. Similarly, we can determine for any student, all of the classes in which
the student is registered.

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
Polynomial Manipulation

The polynomial manipulations such as


addition, subtraction etc. can be performed
using linked list.
Addition of two polynomial
Declaration for linked list implementation
of polynomial ADT
Example
def __init__(self, power, coeff):
self.power = power Poly1 = 5x4 + 3x3 + 2x + 6
self.coeff = coeff Poly2 = 6x4 + 3x3 + 2x2 + 9
self.next = None Poly3 = 11x4 + 6x3 + 2x2 + 2x + 15

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
def _ _add_ _(self, rhsPoly): power = poly1.power or power = poly2.power
newPoly = Polynomial() coeff = poly1.coeff + poly2.coeff
poly1 = self._polyHead poly1 = poly1.next
poly2 = rhsPoly._polyHead poly2 = poly2.next

while poly1 is not None and poly2 is not None: newPoly._appendTerm(power, coeff)
if poly1.power > poly2.power: while poly1 is not None:
power = poly1.power newPoly._appendTerm(poly1.power, poly1.coeff)
coeff = poly1.coeff poly1 = poly1.next
poly1 = poly1.next
elif poly1.power < poly2.power: while poly2 is not None:
power = poly2.power newPoly._appendTerm(poly2.power, poly2.coeff)
coeff = poly2.coeff poly2 = poly2.next
poly2 = poly2.next return newPoly
else:

Follow study with JBR Trisea You Tube Channel for Tamil Explanation
thank you

You might also like