You are on page 1of 41

INDEX

Lab
LAB TASK DATE REMARKS
No.

Write a program to find the location of given element


1
by linear search algorithm.
Write a program to find the location of given element
2
by binary search algorithm.
3
Write a program to sort the array by bubble sort
algorithm.
Write a program to sort the array by insertion sort
4
algorithm.
Write a program to update an element in array at
5
given position.
6
Write a program to insert an element into array at
given position.
7 Write a program to delete an element from array.

8
Write a program to find the second largest element
from array.
9 Write a program to find the pattern in the given array

10 Write a program to push an item into stack.

11 Write a program to pop an item from stack.

12 Write a program to insert item in the linked list

13 Write a program to delete item from the linked list

14 Write a program to demonstrate pre order traversal.

15 Write a program to demonstrate in order traversal.

16 Write a program to demonstrate post order traversal.


LAB 01
OBJECT:
Write a program to find the location of given element by linear
search algorithm.
THEORY:
Linear search or sequential search is a method for finding an element within a list It sequentially
checks each element of the list until a match is found or the whole list has been searched.
A linear search runs in at worst linear time and makes at most n comparisons, where n is the
length of the list.

If each element is equally likely to be searched, then linear search has an average case
of n/2 comparisons, but the average case can be affected if the search probabilities for each
element vary.

Linear search is rarely practical because other search algorithms and schemes, such as
the binary search algorithm and hash tables, allow significantly faster searching for all but short
lists.

ALGORITHM:
Linear Search ( Array A, Value x) Let an array A and value to be found in array A is x.
1. Step 1: Set i
2. Step 2: if i > n then go to step 7
3. Step 3: if A[i] = x then go to step 6
4. Step 4: Set i to i + 1
5. Step 5: Go to Step 2
6. Step 6: Print Element x Found at index i and go to step 8
7. Step 7: Print element not found
8. Step 8: Exit

CODE SCREENSHOT:
def LinearSearch(dlist,item):
pos = 0
found = False

while pos < len(dlist) and not found:


if dlist[pos] == item:
found = True
else:
pos = pos + 1

return found, pos

print(LinearSearch([11,23,58,31,56,77,43,12,65,19],31))
SOURCE CODE
def LinearSearch(dlist,item):
pos = 0
found = False

while pos < len(dlist) and not found:


if dlist[pos] == item:
found = True
else:
pos = pos + 1

return found, pos

print(LinearSearch([11,23,58,31,56,77,43,12,65,19],31))

OUTPUT SCREENSHOT:
(TRUE, 3)
LAB 02
OBJECT:
Write a program to find the location of given element by binary
search algorithm.
THEORY:
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm
works on the principle of divide and conquer. For this algorithm to work properly, the data
collection should be in the sorted form.

Binary search looks for a particular item by comparing the middle most item of the collection. If a
match occurs, then the index of item is returned. If the middle item is greater than the item, then
the item is searched in the sub-array to the left of the middle item. Otherwise, the item is searched
for in the sub-array to the right of the middle item. This process continues on the sub-array as well
until the size of the sub array reduces to zero.

ALGORITHM:
(Binary Search) BINARY (DATA, LB,UB,ITEM,LOC)
Here DATA is a sorted array with lower bound LB and upper bound UB, and ITEM is a given item
of information. The variables BEG, END and MID denote, respectively, the beginning, end and
middle locations of a segment of elements of DATA. This algorithm finds the location LOC of
ITEM in DATA or sets LOC = NULL.
1. [Initialize segment variables]
Set BEG := LB, END := UB and MID = INT(BEG + END)/2.
2. Repeat Steps 3 and 4 while BEG ≤ END and DATA[MID] ≠ ITEM.
3. If ITEM < DATA [MID], then:
Set END := MID+1
Else:
Set BEG := MID +1
[End of If structure]
4. Set MID := INT((BEG +END)/2)
[End of Step 2 Loop.]
5. If DATA[MID] = ITEM, then:
Set LOC := MID.
Else:
Set LOC := NULL.
[End of If structure.]
6. Exit.

CODE SCREENSHOT:
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l)//2
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# Return(-1) if element is not present
return -1
# Test Array
arr = [ 11, 13, 17, 24, 26, 28 ]
print("ELEMENTS OF ARRAY: \n")
#Displaying array element
for i in range(len(arr)):
print(arr[i],end = ' ')
#Input to search in array
x=int(input("\n\nENTER ELEMENT TO FIND : "))
result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:
print ("\n\nELEMENT IS PRESENT AT INDEX : ", result)
else:
print ("\n\nELEMENT IS NOT PRESENT IN ARRAY")

SOURCE CODE
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l)//2
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# Return(-1) if element is not present
return -1

# Test Array
arr = [ 11, 13, 17, 24, 26, 28 ]
print("ELEMENTS OF ARRAY: \n")
#Displaying array element
for i in range(len(arr)):
print(arr[i],end = ' ')
#Input to search in array
x=int(input("\n\nENTER ELEMENT TO FIND : "))
result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:
print ("\n\nELEMENT IS PRESENT AT INDEX : ", result)
else:
print ("\n\nELEMENT IS NOT PRESENT IN ARRAY")

OUTPUT SCREENSHOT:
LAB 03
OBJECT:
Write a program to sort the array by bubble sort algorithm.
THEORY:
Bubble Sort is a simple algorithm which is used to sort a given set of n elements provided in form
of an array with n number of elements. Bubble Sort compares all the element one by one and sort
them based on their values.

If the given array has to be sorted in ascending order, then bubble sort will start by comparing the
first element of the array with the second element, if the first element is greater than the second
element, it will swap both the elements, and then move on to compare the second and the third
element, and so on.

If we have total n elements, then we need to repeat this process for n-1 times.

It is known as bubble sort, because with every complete iteration the largest element in the given
array, bubbles up towards the last place or the highest index, just like a water bubble rises up to the
water surface.

Sorting takes place by stepping through all the elements one-by-one and comparing it with the
adjacent element and swapping them if required.

ALGORITHM:
1. bubbleSort(array)
2. for i<-1 to indexOfLastUnsortedElement-1
3. If leftElement>rightElement
4. Swap leftElement and rightElement
5. end bubbleSort [End of If structure.]
Exit.

CODE SCREENSHOT:
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l)//2
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# Return(-1) if element is not present
return -1
# Test Array
arr = [ 11, 13, 17, 24, 26, 28 ]
print("ELEMENTS OF ARRAY: \n")
#Displaying array element
for i in range(len(arr)):
print(arr[i],end = ' ')
#Input to search in array
x=int(input("\n\nENTER ELEMENT TO FIND : "))
result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:
print ("\n\nELEMENT IS PRESENT AT INDEX : ", result)
else:
print ("\n\nELEMENT IS NOT PRESENT IN ARRAY")

SOURCE CODE
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l)//2
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# Return(-1) if element is not present
return -1

# Test Array
arr = [ 11, 13, 17, 24, 26, 28 ]
print("ELEMENTS OF ARRAY: \n")
#Displaying array element
for i in range(len(arr)):
print(arr[i],end = ' ')
#Input to search in array
x=int(input("\n\nENTER ELEMENT TO FIND : "))
result = binarySearch(arr, 0, len(arr)-1, x)
if result != -1:
print ("\n\nELEMENT IS PRESENT AT INDEX : ", result)
else:
print ("\n\nELEMENT IS NOT PRESENT IN ARRAY")

OUTPUT SCREENSHOT:
LAB 04
OBJECT:
Write a program to sort the array by insertion sort algorithm.
THEORY:
Insertion sort is the sorting mechanism where the sorted array is built having one item at a time.
The array elements are compared with each other sequentially and then arranged simultaneously
in some particular order. The analogy can be understood from the style we arrange a deck of cards.
This sort works on the principle of inserting an element at a particular position, hence the name
Insertion Sort.

The first element in the array is assumed to be sorted. The second element is taken and stored
separately. This element is compared with the elements before it (i.ethe first element). If this
element is smaller than the first element, they are swapped.
Now, the first two elements are sorted. The third element is taken and compared with the
elements before it. It is placed just behind the element smaller than it. If there is no element
smaller than it, then it is placed at the first position.

In a similar way, every unsorted element is placed at its correct position.

ALGORITHM:
1. for j = 2 to n
2. key ← A [j]
3. // Insert A[j] into the sorted sequence A[1..j-1]
4. j←i–1
5. while i > 0 and A[i] > key
6. A[i+1] ← A[i]
7. i←i–1
8. A[j+1] ← key

CODE SCREENSHOT:
# Insertion sort in Python
def insertionSort(array):

for step in range(1, len(array)):


key = array[step]
j=step-1
while j>=0 and key<array[j]:
# For descending order, change key<array[j] to key>array[j].
array[j+1] = array[j]
j = j-1
array[j+1]=key
data = [9, 5, 1, 4, 3]
insertionSort(data)
print("Sorted Array in Ascending Order:")
print(data)
SOURCE CODE
def insertionSort(array):
for step in range(1, len(array)):
key = array[step]
j=step-1
while j>=0 and key<array[j]:
# For descending order, change key<array[j] to key>array[j].
array[j+1] = array[j]
j = j-1
array[j+1]=key
data = [9, 5, 1, 4, 3]
insertionSort(data)
print("Sorted Array in Ascending Order:")
print(data)

OUTPUT SCREENSHOT:
LAB 05
OBJECT:
Write a program to update an element in array at given
position.
THEORY:
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple
items of the same type together. Some of the basic operations that can be performed or those
supported by an array include updating of an existing element from the array at a given index, also
known as Update Operation.

ALGORITHM:
Consider LA is a linear array with N elements and K is a positive integer such that K<=N.
Following is the algorithm to update an element available at the Kth position of LA.
1. Start
2. Set LA[K-1] = ITEM
3. Stop

CODE SCREENSHOT:
#creating an array
arr=[1,2,3,4,5]
#finding length of an array
n=len(arr)
print("ARRAY ELEMENTS:")
for i in range(n):
print(arr[i],end=" ")
print("\n")

#updating an element in an array


arr[1]=10
print("UPDATED ARRAY ELEMENTS:")
for j in range(n):
print(arr[j],end=" ")

SOURCE CODE
#creating an array
arr=[1,2,3,4,5]
#finding length of an array
n=len(arr)
print("ARRAY ELEMENTS:")
for i in range(n):
print(arr[i],end=" ")
print("\n")
#updating an element in an array
arr[1]=10
print("UPDATED ARRAY ELEMENTS:")
for j in range(n):
print(arr[j],end=" ")

OUTPUT SCREENSHOT:
LAB 06
OBJECT:
Write a program to insert an element into array at given
position.
THEORY:
Array is a container which can hold a fix number of items and these items should be of the same
type. Most of the data structures make use of arrays to implement their algorithms. Following are
the important terms to understand the concept of Array.

Element − Each item stored in an array is called an element.

Index − Each location of an element in an array has a numerical index, which is used to identify the
element.

Arrays can be declared in various ways in different languages.

As per the above illustration, following are the important points to be considered.

Index starts with 0.

Array length is 10 which means it can store 10 elements.

Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9.

Insert operation is to insert one or more data elements into an array. Based on the requirement, a
new element can be added at the beginning, end, or any given index of array.

Here, we see a practical implementation of insertion operation, where we add data at given index
of the array

ALGORITHM:
Let Array be a linear unordered array of MAX elements.
Let LA be a Linear Array (unordered) with N elements and K is a positive integer such that K<=N.
Following is the algorithm where ITEM is inserted into the Kth position of LA .
1. Start
2. [Initialize Counter] Set J:=N
3. Repeat steps 4 and 5 while J>=K
4. [Move Jth element Downward] Set LA[J+1] :=LA[J]
5. [Decrease Counter] set J:=J-1
[End of Step 2 loop]
6. [Insert Element] Set LA[K]:=ITEM
7. [Reset N] Set N:=N+1
8. Exit

CODE SCREENSHOT:
def insert(arr,x,k):
return arr[:k]+[x]+arr[k:]
arr=[1,2,4,3]
print("ARRAY BEFORE INSERTION")
print(arr)
print("\nENTER ELEMENT TO BE INSERTED")
x=int(input(""))
print("\nENTER INDEX")
y=int(input(""))
print("\nAFTER INSERTION")
print(insert(arr,x,y))

SOURCE CODE
def insert(arr,x,k):
return arr[:k]+[x]+arr[k:]
arr=[1,2,4,3]
print("ARRAY BEFORE INSERTION")
print(arr)
print("\nENTER ELEMENT TO BE INSERTED")
x=int(input(""))
print("\nENTER INDEX")
y=int(input(""))
print("\nAFTER INSERTION")
print(insert(arr,x,y))

OUTPUT SCREEN
LAB 07
OBJECT:
Write a program to delete element from array.
THEORY:
Array is a container which can hold a fix number of items and these items should be of the same
type. Most of the data structures make use of arrays to implement their algorithms. Following are
the important terms to understand the concept of Array.
Element − Each item stored in an array is called an element.
Index − Each location of an element in an array has a numerical index, which is used to identify
the element.
Deletion − Deletes an element at the given index.

ALGORITHM:
1. Start
2. Set J=K
3. Repeat steps 4 and 5 until J < N
4. Set LA[J] = LA[J+1]
5. Set J=J+1
6. Set N=N-1
7. Stop

CODE SCREENSHOT:
python program to remove a given element from an array
# This function removes an element x from arr[] and
# returns new size after removal.
# Returned size is n-1 when element is present.
# Otherwise 0 is returned to indicate failure.
def deleteElement(arr,n,x):

# If x is last element
if arr[n-1]==x:
return n-1

# Start from rightmost element and keep moving


# elements one position ahead.

prev = arr[n-1]
for i in range(n-2,1,-1):
if arr[i]!=x:
curr = arr[i]
arr[i] = prev
prev = curr

# If element was not found


if i<0:
return 0

# Else move the next element in place of x


arr[i] = prev
return n-1
# Driver code
arr = [11,15,6,8,9,10]
n = len(arr)
x=6
n = deleteElement(arr,n,x)
print("Modified array is")
for i in range(n):
print(arr[i],end=" ")

SOURCE CODE
# This function removes an element x from arr[] and
# returns new size after removal.
# Returned size is n-1 when element is present.
# Otherwise 0 is returned to indicate failure.
def deleteElement(arr,n,x):

# If x is last element
if arr[n-1]==x:
return n-1

# Start from rightmost element and keep moving


# elements one position ahead.

prev = arr[n-1]
for i in range(n-2,1,-1):
if arr[i]!=x:
curr = arr[i]
arr[i] = prev
prev = curr

# If element was not found


if i<0:
return 0

# Else move the next element in place of x


arr[i] = prev
return n-1
# Driver code
arr = [11,15,6,8,9,10]
n = len(arr)
x=6
n = deleteElement(arr,n,x)
print("Modified array is")
for i in range(n):
print(arr[i],end=" ")

OUTPUT SCREENSHOT:
LAB 08
OBJECT:
Write a program to find the second largest element from array.
THEORY:
Given an array of integers, our task is to write a program that efficiently finds the second largest
element present in the array.
A simple solution will be first sort the array in descending order and then return the second
element from the sorted array. The time complexity of this solution is O(nlogn).
A Better Solution is to traverse the array twice. In the first traversal find the maximum element.
In the second traversal find the greatest element less than the element obtained in first traversal.
The time complexity of this solution is O(n).
A more Efficient Solution can be to find the second largest element in a single traversal.

ALGORITHM:
1) Initialize two variables first and second to INT_MIN as,
first = second = INT_MIN
2) Start traversing the array,
a) If the current element in array say arr[i] is greater
than first. Then update first and second as,
second = first
first = arr[i]
b) If the current element is in between first and second,
then update second to store the value of current variable as
second = arr[i]
3) Return the value stored in second.

CODE SCREENSHOT:
# Function to print the
# second largest elements
def print2largest(arr,arr_size):

# There should be atleast


# two elements
if (arr_size < 2):

print(" Invalid Input ")


return

first = second = -2147483648


for i in range(arr_size):

# If current element is
# smaller than first
# then update both
# first and second
if (arr[i] > first):
second = first
first = arr[i]

# If arr[i] is in
# between first and
# second then update second
elif (arr[i] > second and arr[i] != first):
second = arr[i]

if (second == -2147483648):
print("There is no second largest element")
else:
print("The second largest element is", second)

# Driver program to test


# above function
arr = [12, 35, 1, 10, 34, 1]
n =len(arr)

print2largest(arr, n)

SOURCE CODE
# Function to print the
# second largest elements
def print2largest(arr,arr_size):

# There should be atleast


# two elements
if (arr_size < 2):

print(" Invalid Input ")


return

first = second = -2147483648


for i in range(arr_size):

# If current element is
# smaller than first
# then update both
# first and second
if (arr[i] > first):

second = first
first = arr[i]

# If arr[i] is in
# between first and
# second then update second
elif (arr[i] > second and arr[i] != first):
second = arr[i]

if (second == -2147483648):
print("There is no second largest element")
else:
print("The second largest element is", second)
# Driver program to test
# above function
arr = [12, 35, 1, 10, 34, 1]
n =len(arr)

print2largest(arr, n)

OUTPUT SCREENSHOT:
LAB 09
OBJECT:
Write a program to find the pattern in the given array
THEORY:
Pattern searching is an important problem in computer science. When we do search for a string in
notepad/word file or browser or database, pattern searching algorithms are used to show the search
results.

Pattern Matching addresses the problem of finding all occurrences of a pattern string in a text
string. Pattern matching algorithms have many practical applications. Computational molecular
biology and the World Wide Web provide settings in which efficient pattern matching algorithms
are essential. New problems are constantly being defined. Original data structures are introduced
and existing data structures are enhanced to provide more efficient solutions to pattern matching
problems. In this survey, we review pattern matching algorithms in one and two dimensions. We
focus on several specific problems, among them small space pattern matching, parameterized
matching, and dictionary matching. We also discuss the indexing problem, for which the classical
data structure is the suffix tree, or alternatively, the suffix array.

ALGORITHM:
(Pattern Matching) P and T are strings with lengths R and S, respectively, and are stored as arrays
with one character per element. This algorithm finds the INDEX of P in T.
[Initialize] Set K:= 1 and MAX:=S-R+1.
Repeat Steps 3 to 5 while K<=MAX:
Repeat for L=1 to R: [Tests each character of P]
If P[L]=/= T[K+L-1], then: Go to Step 5.
[End of inner loop.]
[Success.] Set INDEX:=K, and EXIT.
Set K:=K+1.
[End of Step 2 outer loop.]
[Failure.] Set INDEX:=0.
Exit.

CODE SCREENSHOT:
import re
while True:
print("ENTER A PATTERN TO SEARCH FROM A GIVEN TEXT : ")
patterns = [input("")]
text = ‘AN INVESTMENT IN KNOWLEDGE PAYS THE BEST INTREST’
print ("TEXT : " ,text)

for i in patterns:
print('Looking for "%s" ' % (i), end=' ')
if re.search(i, text):
print('\n\nfound a match!')
else:
print('no match')

SOURCE CODE
import re
while True:
print("ENTER A PATTERN TO SEARCH FROM A GIVEN TEXT : ")
patterns = [input("")]
text = ‘AN INVESTMENT IN KNOWLEDGE PAYS THE BEST INTREST’
print ("TEXT : " ,text)

for i in patterns:
print('Looking for "%s" ' % (i), end=' ')
if re.search(i, text):
print('\n\nfound a match!')
else:
print('no match')

OUTPUT SCREENSHOT:
LAB 10
OBJECT:
Write a program to push an item into stack.
THEORY:
Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new
element is added at one end and (top) an element is removed from that end only.
stack::push()
push() function is used to insert an element at the top of the stack. The element is added to the
stack container and the size of the stack is increased by 1.

ALGORITHM:
This procedure pushes an ITEM onto a STACK. TOP is the location of the last item in STACK and
MAXSTK is the size of the stack.
STEPS:
1.[Stack already filled?]
if TOP=MAXSTK then PRINT “Overflow” and EXIT
2.Set TOP=TOP+1
3.Set STACK[TOP]=ITEM
4.EXIT

CODE SCREENSHOT:
class Stack:

def __init__(self):
self.stack = []

def add(self, dataval):


# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
# Use peek to look at the top of the stack

def peek(self):
return self.stack[-1]

AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.peek()
print(AStack.peek())
AStack.add("Wed")
AStack.add("Thu")
print(AStack.peek())
SOURCE CODE
class Stack:

def __init__(self):
self.stack = []

def add(self, dataval):


# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
# Use peek to look at the top of the stack

def peek(self):
return self.stack[-1]

AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.peek()
print(AStack.peek())
AStack.add("Wed")
AStack.add("Thu")
print(AStack.peek())

OUTPUT SCREENSHOT:
LAB 11
OBJECT:
Write a program to pop an item from stack.
THEORY:
Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new
element is added at one end and (top) an element is removed from that end only.
stack::pop()
pop() function is used to remove an element from the top of the stack(newest element in the
stack). The element is removed to the stack container and the size of the stack is decreased by 1.

ALGORITHM:
This procedure pops the last item from a STACK. TOP is the location of the last item in STACK
which is to be popped.
STEPS:
1.[Stack has an item?]
if TOP=NULL then PRINT “Underflow” and EXIT
2.Set STACK[TOP]=ITEM
3.Set TOP=TOP-1
4.EXIT

CODE SCREENSHOT:
class Stack:

def __init__(self):
self.stack = []

def add(self, dataval):


# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False

# Use list pop method to remove element


def remove(self):
if len(self.stack) <= 0:
return ("No element in the Stack")
else:
return self.stack.pop()

AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())
SOURCE CODE
class Stack:

def __init__(self):
self.stack = []

def add(self, dataval):


# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False

# Use list pop method to remove element


def remove(self):
if len(self.stack) <= 0:
return ("No element in the Stack")
else:
return self.stack.pop()

AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())

OUTPUT SCREENSHOT:
LAB 12
OBJECT:
Write a program to insert item in the linked list
THEORY:
Inserting element in the linked list involves reassigning the pointers from the existing nodes to the
newly inserted node. Depending on whether the new data element is getting inserted at the
beginning or at the middle or at the end of the linked list, we have the below scenarios.

ALGORITHM:
In this algorithm a node X is inserted at the beginning of a linked list. The Linked List is being
pointed by a pointer First at the beginning.
STEPS:
1.X=new node;
2.Read(DATA(X);
3.If (FIRST=NULL) then
{
First=X;
NEXT(X)=NULL;
}
Else
{
NEXT(X)=First;
First=X;
}
4.END
INSERT AFTER A NODE
Let List be a pointer to a linked list. In this algorithm a node X is inserted in the list after a node
with data part equal to ‘VAL’. A pointer ptr travels the list in such a way that each visited node is
checked for data part equal to ‘VAL’. If such a node is found then node X is inserted after the same.
STEPS:
1. Ptr=List;
2. While (ptr<>NULL) repeat steps 3 to 4
3. If (DATA(ptr)=’VAL’) then
{
X=new node
Read (DATA(X);
NEXT(X)=NEXT(ptr)
NEXT(ptr)=X;
BREAK;}
4.ptr=NEXT(ptr)
[end of while]
5.END.
It may be noted in the above algorithm that in step 3 a function exit() has been used. The purpose
of this function is to leave the while loop.
INSERT BEFORE A NODE
Let LIST be a pointer to a linked list. In this algorithm a node X is inserted in the list before a node
with data part equal to ‘VAL’ Two pointers ptr and back travel the list in such a way that each
visited node is checked for data part equal to ‘VAL’. If such a node is found then ptr points to the
selected node and back point to immediate previous node in the list. The node X is inserted before
the selected node.
STEPS:
1.ptr=LIST
[check if the first node is the desired one]
2.If(data(ptr)=’VAL’) then
{
X=new node;
Read DATA(X);
NEXT(X)=LIST;
LIST=X;
STOP;
}
3.While(ptr<>NULL ) repeat step 4 to 6
4.back=ptr;
5.ptr=NEXT(ptr);
6.If(DATA(ptr)=’VAL’)then
{
X=new node;
Read DATA(X);
NEXT(X)=ptr;
NEXT(back)=X;
EXIT;
}
[end of while loop]
7.END

CODE SCREENSHOT:
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None

class SLinkedList:
def __init__(self):
self.headval = None

# Function to add node


def Inbetween(self,middle_node,newdata):
if middle_node is None:
print("The mentioned node is absent")
return

NewNode = Node(newdata)
NewNode.nextval = middle_node.nextval
middle_node.nextval = NewNode

# Print the linked list


def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval

list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Thu")

list.headval.nextval = e2
e2.nextval = e3

list.Inbetween(list.headval.nextval,"Fri")

list.listprint()

SOURCE CODE
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None

class SLinkedList:
def __init__(self):
self.headval = None

# Function to add node


def Inbetween(self,middle_node,newdata):
if middle_node is None:
print("The mentioned node is absent")
return

NewNode = Node(newdata)
NewNode.nextval = middle_node.nextval
middle_node.nextval = NewNode

# Print the linked list


def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval

list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Thu")

list.headval.nextval = e2
e2.nextval = e3

list.Inbetween(list.headval.nextval,"Fri")

list.listprint()
OUTPUT SCREENSHOT:
LAB 13
OBJECT:
Write a program to delete item from the linked list
THEORY:
A delete operation involves the following two steps:
search the list for the node which is to be deleted.
delete the node.

ALGORITHM:
A algorithm for the deletion of a node from a linked list is given below:
DELETE:
Let List be a pointer to a linked list. In this algorithm a node with data value equal to ‘VAL’.
Deleted from the list. Two pointers ptr and back travel the list in such a way that each visited node
is checked for data equal to ‘VAL’. If such a node is found then ptr points to the selected node and
back points to immediate previous node in the list. The selected node is deleted from the list.
STEPS:[CHECK IF THE FIRST NODE IS THE DESIRED ONE]
1. If (DATA(list)=’VAL’)then
{
Ptr=LIST;
LIST=NEXT(list);
Delete ptr;
Stop;
}
Back=list;
Ptr=list;
2. While (ptr<>NULL) repeat step 3 to 5
3. If (DATA (ptr)=’VAL’) then
{
NEXT (back)=NEXT (ptr);
Delete ptr;
Exit;
}
4. back=ptr;
5. ptr=next(ptr);
[end of while loop]
6. END
DELETION FROM THE START
Deleting an element or item from the start of the linked list is straightforward. We have to set the
reference of the start_node to the second node which we can do by simply assigning the value of
the reference of the start node (which is pointing to the second node) to the start node as shown
below:

Def delete_at_start(self):
If self.start_node is None:
Print ("The list has no element to delete")
Return self.start_node = self.start_node.ref :

Deletion at the End


To delete an element from the end of the list, we simply have to iterate through the linked list till
the second last element, and then we need to set the reference of the second last element to none,
which will convert the second last element to last element.
The script for the function delete_at_end is as follows:
Def delete_at_end(self):
If self.start_node is None:
print("The list has no element to delete")
return
n = self.start_node
while n.ref.ref is not None:
n = n.ref
n.ref = None

CODE SCREENSHOT:
class Node:
def __init__(self, data=None):
self.data = data
self.next = None

class SLinkedList:
def __init__(self):
self.head = None

def Atbegining(self, data_in):


NewNode = Node(data_in)
NewNode.next = self.head
self.head = NewNode

# Function to remove node


def RemoveNode(self, Removekey):

HeadVal = self.head

if (HeadVal is not None):


if (HeadVal.data == Removekey):
self.head = HeadVal.next
HeadVal = None
return

while (HeadVal is not None):


if HeadVal.data == Removekey:
break
prev = HeadVal
HeadVal = HeadVal.next

if (HeadVal == None):
return

prev.next = HeadVal.next

HeadVal = None

def LListprint(self):
printval = self.head
while (printval):
print(printval.data),
printval = printval.next
llist = SLinkedList()
llist.Atbegining("Mon")
llist.Atbegining("Tue")
llist.Atbegining("Wed")
llist.Atbegining("Thu")
llist.RemoveNode("Tue")
llist.LListprint()

SOURCE CODE
class Node:
def __init__(self, data=None):
self.data = data
self.next = None

class SLinkedList:
def __init__(self):
self.head = None

def Atbegining(self, data_in):


NewNode = Node(data_in)
NewNode.next = self.head
self.head = NewNode

# Function to remove node


def RemoveNode(self, Removekey):

HeadVal = self.head

if (HeadVal is not None):


if (HeadVal.data == Removekey):
self.head = HeadVal.next
HeadVal = None
return

while (HeadVal is not None):


if HeadVal.data == Removekey:
break
prev = HeadVal
HeadVal = HeadVal.next

if (HeadVal == None):
return

prev.next = HeadVal.next

HeadVal = None

def LListprint(self):
printval = self.head
while (printval):
print(printval.data),
printval = printval.next
llist = SLinkedList()
llist.Atbegining("Mon")
llist.Atbegining("Tue")
llist.Atbegining("Wed")
llist.Atbegining("Thu")
llist.RemoveNode("Tue")
llist.LListprint()

OUTPUT SCREENSHOT:
LAB 14
OBJECT:
Write a program to demonstrate pre order traversal.
THEORY:
In this traversal method, the root node is visited first, then the left subtree and finally the right
subtree.
In the below python program, we use the Node class to create place holders for the root node as
well as the left and right nodes. Then we create a insert function to add data to the tree. Finally the
Pre-order traversal logic is implemented by creating an empty list and adding the root node first
followed by the left node. At last the right node is added to complete the Pre-order traversal. This
process is repeated for each sub-tree until all the nodes are traversed.

ALGORITHM:
1) Return the root node value.
2) Traverse the left subtree by recursively calling the pre-order function.
3) Traverse the right subtree by recursively calling the pre-order function.

CODE SCREENSHOT:
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None

# create nodes
root = Node('A')
n1 = Node('B')
n2 = Node('C')
n3 = Node('D')
n4 = Node('E')

# setup children
root.left = n1
root.right = n2
n1.left = n3
n1.right = n4

def pre_order(root, nodes):


nodes.append(root.data)
if root and root.left:
pre_order(root.left, nodes)
if root and root.right:
pre_order(root.right, nodes)
return nodes
print (pre_order(root,[]))
SOURCE CODE
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None

# create nodes
root = Node('A')
n1 = Node('B')
n2 = Node('C')
n3 = Node('D')
n4 = Node('E')

# setup children
root.left = n1
root.right = n2
n1.left = n3
n1.right = n4

def pre_order(root, nodes):


nodes.append(root.data)
if root and root.left:
pre_order(root.left, nodes)
if root and root.right:
pre_order(root.right, nodes)
return nodes
print (pre_order(root,[]))

OUTPUT SCREENSHOT:
LAB 15
OBJECT:
Write a program to demonstrate in order traversal.
THEORY:
In this traversal method, the root node is visited last, hence the name. First we traverse the left
subtree, then the right subtree and finally the root node.
In the below python program, we use the Node class to create place holders for the root node as
well as the left and right nodes. Then we create a insert function to add data to the tree. Finally the
Post-order traversal logic is implemented by creating an empty list and adding the left node first
followed by the right node. At last the root or parent node is added to complete the Post-order
traversal. This process is repeated for each sub-tree until all the nodes are traversed.

ALGORITHM:
1) Traverse the left subtree by recursively calling the in-order function.
2) Return the root node value.
3) Traverse the right subtree by recursively calling the in-order function.

CODE SCREENSHOT:
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None

# create nodes
root = Node('A')
n1 = Node('B')
n2 = Node('C')
n3 = Node('D')
n4 = Node('E')

# setup children
root.left = n1
root.right = n2
n1.left = n3
n1.right = n4

def in_order(root, nodes):


if root and root.left:
in_order(root.left, nodes)
nodes.append(root.data)
if root and root.right:
in_order(root.right, nodes)
return nodes

print ( in_order(root, []) )


SOURCE CODE
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None

# create nodes
root = Node('A')
n1 = Node('B')
n2 = Node('C')
n3 = Node('D')
n4 = Node('E')

# setup children
root.left = n1
root.right = n2
n1.left = n3
n1.right = n4

def in_order(root, nodes):


if root and root.left:
in_order(root.left, nodes)
nodes.append(root.data)
if root and root.right:
in_order(root.right, nodes)
return nodes

print ( in_order(root, []) )

OUTPUT SCREENSHOT:
LAB 16
OBJECT:
Write a program to demonstrate post order traversal.
THEORY:
In this traversal method, the left subtree is visited first, then the root and later the right sub-tree.
We should always remember that every node may represent a subtree itself.
In the below python program, we use the Node class to create place holders for the root node as
well as the left and right nodes. Then we create a insert function to add data to the tree. Finally the
Inorder traversal logic is implemented by creating an empty list and adding the left node first
followed by the root or parent node. At last the left node is added to complete the Inorder
traversal. This process is repeated for each sub-tree until all the nodes are traversed.

ALGORITHM:
1) Traverse the left subtree by recursively calling the post-order function.
2) Traverse the right subtree by recursively calling the post-order function.
3) Return the root node value.

CODE SCREENSHOT:
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None

# create nodes
root = Node('A')
n1 = Node('B')
n2 = Node('C')
n3 = Node('D')
n4 = Node('E')

# setup children
root.left = n1
root.right = n2
n1.left = n3
n1.right = n4

def post_order(root, nodes):


if root and root.left:
post_order(root.left, nodes)
if root and root.right:
post_order(root.right, nodes)
nodes.append(root.data)
return nodes

print ( post_order(root, []) )


SOURCE CODE
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None

# create nodes
root = Node('A')
n1 = Node('B')
n2 = Node('C')
n3 = Node('D')
n4 = Node('E')

# setup children
root.left = n1
root.right = n2
n1.left = n3
n1.right = n4

def post_order(root, nodes):


if root and root.left:
post_order(root.left, nodes)
if root and root.right:
post_order(root.right, nodes)
nodes.append(root.data)
return nodes

print ( post_order(root, []) )

OUTPUT SCREENSHOT:

You might also like