0% found this document useful (0 votes)
17 views51 pages

AD3271 Data Structures Design LAB Observation

Uploaded by

Cat
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)
17 views51 pages

AD3271 Data Structures Design LAB Observation

Uploaded by

Cat
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/ 51

OBSERVATION

NAME:
REG NO:
EXP 1: Implement recursive algorithms in Python
Program 1.1: Linear Search
AIM:
To write a python program to do Linear Search in an unsorted list using a search key.
ALGORITHM:

1. Start the program.


2. Define the function recursive_linear_search(arr, target, index=0).
o If the index is equal to the length of arr, return an empty list [].
o If arr[index] is equal to target, return a list containing index + 1.
o Otherwise, make a recursive call to recursive_linear_search with arr, target,
and index + 1.
3. Create an empty list l.
4. Prompt the user to enter the number of elements to be inserted into the list.
5. Read the input as an integer and store it in the variable n.
6. Print the message "Enter [n] values" to indicate that the user should enter n values.
7. Repeat n times: a. Prompt the user to enter a value. b. Read the input as an integer
and append it to the list l.
8. Prompt the user to enter the element to be searched.
9. Read the input as an integer and store it in the variable s.
10. Call the recursive_linear_search function with arguments l, s, and an initial index
value of 0.
11. Receive the return value from the recursive_linear_search function and store it in
the variable position.
12. Check if the position is not equal to an empty list []:
o If true, print the message "The element [s] is found at position: [position[0]]",
where [s] represents the target element and [position[0]] represents the
index.
o If false, print the message "The element [s] is not found in the list", where [s]
represents the target element.
13. End the program.

1
PROGRAM:

OUTPUT:

RESULT:
Thus, the python program to do Linear Search in an unsorted list using a search key is
executed successfully and output is verified.

2
Program 1.2: Binary Search
AIM:
To write a python program to do Binary Search in a sorted list using a search key.
ALGORITHM:
1. Start the program.
2. Read the size of the list from the user and store it in a variable 'size'.
3. Create an empty list 'lst' to store the elements.
4. Repeat 'size' times:
o Read an element from the user and store it in a variable 'num'.
o Append 'num' to the 'lst' list.
5. Sort the 'lst' list in ascending order.
6. Print "Sorted order:" to indicate the display of sorted elements.
7. Print the elements of the 'lst' list.
8. Read the number to search for from the user and store it in a variable 'search_key'.
9. Call the binary_search function with arguments 'lst', 'search_key', 0, and 'size - 1'.
10. The binary_search function:
o If 'low' is greater than 'high', return False (base case) as the target is not found
in the current portion of the list.
o Calculate the middle index by taking the floor division of ('low' + 'high') / 2 and
store it in a variable 'mid'.
o If 'search_key' is equal to 'lst[mid]', return True (base case) as the target is
found.
o If 'search_key' is less than 'lst[mid]', make a recursive call to binary_search with
arguments 'lst', 'search_key', 'low', and 'mid - 1'.
o If 'search_key' is greater than 'lst[mid]', make a recursive call to binary_search
with arguments 'lst', 'search_key', 'mid + 1', and 'high'.
11. If the return value from the binary_search function is True: 11.1 Print "Number",
'search_key', "was found in the list at position", 'index + 1', where 'index' is the index
of the target value in the 'lst' list.
12. If the return value from the binary_search function is False: 12.1 Print "Number",
'search_key', "was not found in the list".
13. End the program.

3
PROGRAM:

OUTPUT:

RESULT:
Thus, the python program to do Binary Search in a sorted list using a search key is executed
successfully and output is verified.

4
Program 1.3: Fibonacci Search
AIM:
To write a python program to do Fibonacci Search in a sorted list using Fibonacci series.
ALGORITHM:
1. Start the program.
2. Prompt the user to enter the size of the list.
3. Create an empty list to store the elements.
4. Iterate for the given size:
o Prompt the user to enter an element.
o Convert the input to an integer and append it to the list.
5. Sort the list in ascending order.
6. Print the sorted list.
7. Prompt the user to enter the number to search for.
8. Perform Fibonacci search:
o Initialize Fibonacci sequence variables: m2 = 0, m1 = 1, m = m1 + m2.
o Update the Fibonacci variables until m becomes greater than or equal to the
length of the list.
o Set the offset to 0.
o Repeat until m2 becomes 0:
▪ Calculate the index as min(offset + m2, len(lst) - 1).
▪ If the element at the index is equal to the search key, return the
index.
▪ If the element is greater than the search key, update the Fibonacci
variables and set m = m2, m1 = m1 - m2, m2 = m - m1.
▪ If the element is smaller than the search key, update the Fibonacci
variables and set m = m1, m1 = m2, m2 = m - m1, and update the
offset.
o If the search key is not found, return -1.
9. Check the result of the search:
o If the result is not -1, print "The value [key] is found at index [result]."
o If the result is -1, print "The value [key] is not found in the list."
10. End the program.

5
PROGRAM:

6
OUTPUT:

RESULT:
Thus, the python program to do Fibonacci Search in a sorted list using Fibonacci series is
executed successfully and output is verified.

7
EXP 2: Implement List ADT using Python arrays
Program 2.1: Array Implementation of lists.
AIM:
To write a python program to Implement List ADT using Python arrays.
ALGORITHM:
1. Start the program.
2. Create an instance of the List class to represent the list.
3. Enter a loop that repeats indefinitely:
4. Display a menu of options for the user to choose from.
5. Prompt the user to enter their choice.
6. If the choice is 1:
7. Prompt the user to enter the position and item to insert.
8. Call the insert method of the List instance with the provided position and item.
o Check if the position is valid (not less than 0 or greater than the current size).
o If the list is empty and the position is not 0, display an error message.
o Insert the item at the specified position in the array list.
o Increment the size attribute.
9. If the choice is 2:
10. Prompt the user to enter the position to delete.
11. Call the delete method of the List instance with the provided position.
o Check if the position is valid (not less than 0 or greater than or equal to the
current size).
o If the list is empty, display an error message.
o Delete the item at the specified position from the array list.
o Decrement the size attribute.
12. If the choice is 3:
13. Call the traverse method of the List instance to print the elements in the list.
o Iterate over each item in the array list and print it.
o If the list is empty, print a message stating that the list is empty.
14. If the choice is 4:
15. Prompt the user to enter the item to find.
16. Call the find method of the List instance with the provided item and print the result.
o Iterate over each item in the array list and check if it matches the provided
item.
o If a match is found, return the index of the item.
o If no match is found, return -1.
17. If the choice is 5:
18. Call the length method of the List instance to get the length of the list and print it.
o Return the current value of the size attribute.
19. If the choice is 6:
20. Call the make_empty method of the List instance to clear the list.

8
o Set the array attribute to an empty list [].
o Set the size attribute to 0.
21. If the choice is 7:
22. Exit the loop.
23. If the choice is not valid:
24. Display an error message and prompt the user again.
25. End the program.
PROGRAM:

9
10
OUTPUT:

RESULT:
Thus, the python program to Implement List ADT using Python arrays is executed
successfully and output is verified.

11
EXP 3: Linked list implementations of List
Program 3.1: Singly Linked List.
AIM:
To write a python program to implement a singly linked list and perform various operations
like insertion, deletion, find and traversal on it.
ALGORITHM:
1. Start the program.
2. Create an instance of the SinglyLinkedList class to represent the list.
3. Enter a loop that repeats indefinitely:
4. Display a menu of options for the user to choose from.
5. Prompt the user to enter their choice.
6. If the choice is 1:
7. Prompt the user to enter the data to insert at the beginning.
8. Call the insert_at_beginning method of the SinglyLinkedList instance with the provided
data.
9. Inside insert_at_beginning(data):
o Create a new Node object with the given data.
o Set the next attribute of the new node to the current head of the linked list.
o Update the head of the linked list to be the new node.
10. If the choice is 2:
11. Prompt the user to enter the data to insert at the end.
12. Call the insert_at_end method of the SinglyLinkedList instance with the provided data.
13. Inside insert_at_end(data):
o Create a new Node object with the given data.
o If the linked list is empty (head is None), set the new node as the head of the
linked list.
o Otherwise, traverse the linked list until the last node is reached.
o Set the next attribute of the last node to the new node.
14. If the choice is 3:
15. Prompt the user to enter the data and position to insert.
16. Call the insert_at_position method of the SinglyLinkedList instance with the provided data
and position.
17. Inside insert_at_position(data, position):
o Create a new Node object with the given data.
o If the position is 1, set the next attribute of the new node to the current head
and update the head to be the new node.
o Otherwise, traverse the linked list until the node at position - 1 is reached.
o Set the next attribute of the new node to the next node of the current node.
18. If the choice is 4:
19. Call the delete_at_beginning method of the SinglyLinkedList instance.
20. Inside delete_at_beginning():
o Check if the linked list is empty by verifying if the head is None.
o If the list is not empty, update the head to be the next node, effectively
removing the first node from the linked list.

12
21. If the choice is 5:
22. Call the delete_at_end method of the SinglyLinkedList instance.
23. Inside delete_at_end():
o Check if the linked list is empty by verifying if the head is None.
o If the list is not empty, traverse the linked list until the second-to-last node is
reached.
o Set the next attribute of the second-to-last node to None, effectively removing
the last node from the linked list.
24. If the choice is 6:
25. Prompt the user to enter the position to delete.
26. Call the delete_at_position method of the SinglyLinkedList instance with the provided
position.
27. Inside delete_at_position(position):
o Check if the linked list is empty by verifying if the head is None.
o If the position is 1, update the head to be the next node, effectively removing
the first node from the linked list.
o Otherwise, traverse the linked list until the node at position - 1 is reached.
o Set the next attribute of that node to the node after the current node,
effectively removing the node at the specified position.
28. If the choice is 7:
29. Prompt the user to enter the data to find.
30. Call the find method of the SinglyLinkedList instance with the provided data.
31. Inside find(data):
o Traverse the linked list, keeping track of the current node and a position
counter.
o If the current node's data matches the given data, return the position.
32. If the element is found, display its position.
33. If the element is not found, display a message indicating it was not found.
34. If the choice is 8:
35. Call the traverse method of the SinglyLinkedList instance to display the elements in the
linked list.
36. If the choice is 9:
37. Exit the loop and end the program.
38. If the choice is invalid:
39. Display an error message indicating an invalid choice
40. End the program

13
PROGRAM:

14
15
OUTPUT:

16
RESULT:
Thus, the python to implement a singly linked list and perform various operations like
insertion, deletion, find and traversal on it, is executed successfully and output is verified.

17
Program 3.2: Doubly Linked List.
AIM:
To write a python program to implement a doubly linked list and perform various operations
like insertion, deletion, find and traversal on it.
ALGORITHM:
1. Start the program.
2. Create an instance of the DoublyLinkedList class to represent the list.
3. Enter a loop that repeats indefinitely:
4. Display a menu of options for the user to choose from.
5. Prompt the user to enter their choice.
6. If the choice is 1:
o Prompt the user to enter the data to insert at the beginning.
o Call the insert_at_beginning method of the DoublyLinkedList instance with
the provided data.
o Inside insert_at_beginning(data):
▪ Create a new Node object with the given data.
▪ If the linked list is empty (head is None), set the new node as the head
of the linked list.
▪ Otherwise, set the next attribute of the new node to the current head
node.
▪ Set the prev attribute of the current head node to the new node.
▪ Set the new node as the new head of the linked list.
7. If the choice is 2:
o Prompt the user to enter the data to insert at the end.
o Call the insert_at_end method of the DoublyLinkedList instance with the
provided data.
o Inside insert_at_end(data):
▪ Create a new Node object with the given data.
▪ If the linked list is empty (head is None), set the new node as the head
of the linked list.
▪ Otherwise, traverse the linked list until the last node is reached.
▪ Set the next attribute of the last node to the new node.
▪ Set the prev attribute of the new node to the last node.
8. If the choice is 3:
o Prompt the user to enter the data and position to insert.
o Call the insert_at_position method of the DoublyLinkedList instance with the
provided data and position.
o Inside insert_at_position(data, position):
▪ Check if the position is valid (not less than 1 or greater than the
current size + 1).
▪ If the position is 1, call the insert_at_beginning method with the
provided data.
▪ Otherwise, create a new Node object with the given data.
▪ Traverse the linked list until the position is reached.

18
▪ Set the next attribute of the new node to the current node at the
position.
▪ Set the prev attribute of the new node to the node before the current
node.
▪ Set the next attribute of the node before the current node to the new
node.
▪ Set the prev attribute of the current node at the position to the new
node.
9. If the choice is 4:
o Call the delete_at_beginning method of the DoublyLinkedList instance.
o Inside delete_at_beginning():
▪ Check if the linked list is empty (head is None).
▪ If not empty, set the next attribute of the head node to None.
▪ Set the next node as the new head of the linked list.
10. If the choice is 5:
o Call the delete_at_end method of the DoublyLinkedList instance.
o Inside delete_at_end():
▪ Check if the linked list is empty (head is None).
▪ If not empty, traverse the linked list until the last node is reached.
▪ Set the next attribute of the second-to-last node to None.
11. If the choice is 6:
o Prompt the user to enter the position to delete.
o Call the delete_at_position method of the DoublyLinkedList instance with the
provided position.
o Inside delete_at_position(position):
▪ Check if the position is valid (not less than 1 or greater than the
current size).
▪ If the position is 1, call the delete_at_beginning method.
▪ Traverse the linked list until the position is reached.
▪ Set the next attribute of the node before the current position to the
node after the current position.
▪ Set the prev attribute of the node after the current position to the
node before the current position.
12. If the choice is 7:
o Prompt the user to enter the data to find.
o Call the find method of the DoublyLinkedList instance with the provided data.
o Inside find(data):
▪ Traverse the linked list and compare the data of each node with the
provided data.
▪ If a match is found, return the position of the node.
▪ If no match is found, return None.
13. If the choice is 8:
o Call the traverse_forward method of the DoublyLinkedList instance to display
the elements in the linked list in forward order.
14. If the choice is 9:
o Call the traverse_backward method of the DoublyLinkedList instance to
display the elements in the linked list in backward order.

19
15. If the choice is 10:
o Exit the loop and end the program.
16. If the choice is invalid:
o Display an error message indicating an invalid choice.
17. End the program

PROGRAM:

20
21
22
OUTPUT:

23
RESULT:
Thus, the python program to implement a doubly linked list and perform various operations
like insertion, deletion, find and traversal on it, is executed successfully and output is verified.

24
Program 3.3: Circularly Linked List.
AIM:
To write a python program to implement a circularly linked list and perform various
operations like insertion, deletion, find and traversal on it.
ALGORITHM:
1. Start the program.
2. Create an instance of the CircularLinkedList class to represent the list.
3. Enter a loop that repeats indefinitely:
4. Display a menu of options for the user to choose from.
5. Prompt the user to enter their choice.
6. If the choice is 1:
o Prompt the user to enter the data to insert at the beginning.
o Call the insert_at_beginning method of the CircularLinkedList instance with
the provided data.
o Inside insert_at_beginning(data):
▪ Create a new Node object with the given data.
▪ If the linked list is empty (head is None), set the new node as the head
of the linked list.
▪ Otherwise, set the next attribute of the new node to the current head
node.
▪ Set the next attribute of the last node to the new node.
▪ Set the new node as the new head of the linked list.
7. If the choice is 2:
o Prompt the user to enter the data to insert at the end.
o Call the insert_at_end method of the CircularLinkedList instance with the
provided data.
o Inside insert_at_end(data):
▪ Create a new Node object with the given data.
▪ If the linked list is empty (head is None), set the new node as the head
of the linked list.
▪ Otherwise, traverse the linked list until the last node is reached.
▪ Set the next attribute of the last node to the new node.
▪ Set the next attribute of the new node to the head node.
8. If the choice is 3:
o Prompt the user to enter the data to insert.
o Prompt the user to enter the position to insert (considered as 1 indexing).
o Call the insert_at_position method of the CircularLinkedList instance with the
provided data and position.
o Inside insert_at_position(data, position):
▪ Create a new Node object with the given data.
▪ If the linked list is empty (head is None) and the position is not 1,
display an error message.
▪ If the position is 1, set the new node as the head of the linked list.
▪ Otherwise, traverse the linked list until the position - 1 is reached.

25
▪ Set the next attribute of the new node to the node at the current
position.
▪ Set the next attribute of the node at the current position - 1 to the
new node.
▪ If the current position is the last node, set the next attribute of the
new node to the head node.
9. If the choice is 4:
o Call the delete_at_beginning method of the CircularLinkedList instance to
delete the first node.
10. If the choice is 5:
o Call the delete_at_end method of the CircularLinkedList instance to delete
the last node.
11. If the choice is 6:
o Prompt the user to enter the position to delete (considered as 1 indexing).
o Call the delete_at_position method of the CircularLinkedList instance with
the provided position.
o Inside delete_at_position(position):
▪ If the linked list is empty (head is None), display an error message.
▪ If the position is 1, set the head to the next node and update the last
node's next attribute.
▪ Otherwise, traverse the linked list until the position - 1 is reached.
▪ Set the next attribute of the node at the current position - 1 to the
node after the current position.
▪ If the current position is the last node, update the last node's next
attribute to the head node.
12. If the choice is 7:
o Prompt the user to enter the data to find.
o Call the find method of the CircularLinkedList instance with the provided
data.
o Inside the find(data) method:
▪ If the linked list is empty (head is None), display an error message.
▪ Traverse the linked list and compare the data of each node with the
given data.
▪ If a match is found, return the position of the node (considered as 1
indexing).
▪ If no match is found, display "Element not found."
13. If the choice is 8:
o Call the traverse method of the CircularLinkedList instance to print the
elements of the list.
o Inside the traverse method:
▪ If the linked list is empty (head is None), display "List is empty."
▪ Traverse the linked list starting from the head and print the data of
each node.
▪ Continue traversing until the head node is reached again.
The program continues to loop until the user chooses to exit.
14. End the program

26
PROGRAM:

27
28
29
OUTPUT:

RESULT:
Thus, the python program to implement a circularly linked list and perform various operations
like insertion, deletion, find and traversal on it, is executed successfully and output is verified.

30
EXP 4: Implementation of Stack and Queue ADTs
Program 4.1: A Python program to implement Stack and its operations using list
AIM:
To write a Python program to implement Stack and its operations using list.
ALGORITHM:
1. Start the program.
2. Prompt the user to enter the maximum size of the stack as an integer and store it in the
`max_size` variable.
3. Define a class `Stack` with the following methods:
o `__init__(self, max_size)`: Initialize the stack with an empty list, set the `top` variable
to 0, and store the `max_size` in an instance variable.
o `push(self, item)`: Check if the `top` is less than `max_size`. If true, append the `item`
to the stack list, print "Pushed item: " followed by the value of `item`, and increment
`top` by 1. If the `top` is equal to or exceeds `max_size`, print "Stack overflow".
o `pop(self)`: Check if the stack is not empty using the `is_empty()` method. If not empty,
decrement `top` by 1, remove and return the topmost item from the stack list using
the `pop()` method. If the stack is empty, print "Stack is empty".
o `display(self)`: Check if the stack is not empty using the `is_empty()` method. If not
empty, print "Stack: " followed by the stack list. If the stack is empty, print "Stack is
empty".
o `is_empty(self)`: Check if `top` is equal to 0 and return `True` if it is, or `False`
otherwise.
4. Create an instance of the `Stack` class by passing the `max_size` variable obtained from
user input.
5. Enter an infinite loop using `while True` to provide a menu-driven interface.
6. Print the menu options for the user: "1. Push", "2. Pop", "3. Display", "4. Quit".
7. Prompt the user to enter their choice as an integer.
8. Use conditional statements to check the user's choice and perform the corresponding
action:
o If the choice is 1: Prompt the user to enter the item to push as an integer and store it
in the `item` variable.
o Call the `push(item)` method on the `stack` instance.
o If the choice is 2: Call the `pop()` method on the `stack` instance and store the returned
item in the `item` variable.
o If `item` is not None, print "Popped item: " followed by the value of `item`.
o If the choice is 3: Call the `display()` method on the `stack` instance.
o If the choice is 4: Print "Quitting the program..." and break out of the infinite loop.
o If the choice is not 1, 2, 3, or 4:
o Print "Invalid choice. Please try again."
9. Repeat steps 7-8 until the user chooses to quit by selecting option 4.
10. End the program.

31
PROGRAM:

32
OUTPUT:

RESULT:
Thus, the python program to implement Stack and its operations using list is executed
successfully and output is verified.

33
Program 4.2: A Python program to implement Queue and its operations using list
AIM:
To write a Python program to implement Queue and its operations using list.
ALGORITHM:
1. Start the program.
2. Prompt the user to enter the maximum size of the queue as an integer and store it in the
`max_size` variable.
3. Define a class `Queue` with the following methods:
o `__init__(self, max_size)`: Initialize the queue with an empty list, set the `front`
and `rear` variables to 0, and store the `max_size` in an instance variable.
o `is_empty(self)`: Check if `front` is equal to `rear` and return `True` if it is, or `False`
otherwise.
o `is_full(self)`: Check if `rear` is equal to `max_size` and return `True` if it is, or
`False` otherwise.
o `enqueue(self, item)`: Check if the queue is full using the `is_full()` method. If not
full, append the `item` to the queue list, print "Enqueued to queue: " followed by
the value of `item`, and increment `rear` by 1. If the queue is full, print "Queue is
full".
o `dequeue(self)`: Check if the queue is empty using the `is_empty()` method. If not
empty, remove and return the item at `front` index from the queue list, increment
`front` by 1, and print "Dequeued item: " followed by the value of the dequeued
item. If the queue is empty, print "Queue is empty".
o `display(self)`: Check if the queue is not empty using the `is_empty()` method. If
not empty, print "Queue items: " followed by the queue list from `front` to `rear-
1`. If the queue is empty, print "Queue is empty".
4. Create an instance of the `Queue` class by passing the `max_size` variable obtained from
user input.
5. Enter an infinite loop using `while True` to provide a menu-driven interface.
6. Print the menu options for the user: "1. Enqueue", "2. Dequeue", "3. Display", "4. Quit".
7. Prompt the user to enter their choice as an integer.
8. Use conditional statements to check the user's choice and perform the corresponding
action:
o If the choice is 1: Prompt the user to enter the item to enqueue and store it in the
`item` variable.
o Call the `enqueue(item)` method on the `queue` instance.
o If the choice is 2: Call the `dequeue()` method on the `queue` instance and store
the returned item in the `item` variable.
o If `item` is not None, print "Dequeued item: " followed by the value of `item`.
o If the choice is 3: Call the `display()` method on the `queue` instance.
o If the choice is 4: Print "Quitting the program..." and break out of the infinite loop.
o If the choice is not 1, 2, 3, or 4:
o Print "Invalid choice. Please try again."

34
9. Repeat steps 7-8 until the user chooses to quit by selecting option 4.
10. End the program.
PROGRAM:

35
OUTPUT:

RESULT:
Thus, the python program to implement Queue and its operations using list is executed
successfully and output is verified.

36
EXP 5: Implementation of Stack and Queue using Linked List
Program 5.1: A Python program to implement Stack and its operations using linked list
AIM:
To write a Python program to implement Stack and its operations using linked list.
ALGORITHM:
1. Start the Program
2. Create a class `Node` with attributes `data` and `next`. This class represents a node in the
linked list.
3. Create a class `Stack` with an attribute `top` initially set to `None`. This class represents
the stack and its operations.
4. Define the `is_empty` method in the `Stack` class. This method checks if the stack is empty
by checking if the `top` attribute is `None`. Return `True` if it is empty, otherwise return
`False`.
5. Define the `push` method in the `Stack` class. This method takes an item as input. Create
a new node with the item and set its `next` attribute to the current `top`. Update the `top`
attribute to point to the new node.
6. Define the `pop` method in the `Stack` class. This method removes and returns the top
item from the stack. If the stack is empty (i.e., `top` is `None`), print a message indicating
that the stack is empty and return `None`. Otherwise, store the data of the current `top`
node in a variable. Update the `top` attribute to point to the next node. Return the stored
data.
7. Define the `display` method in the `Stack` class. This method prints the items in the stack
from top to bottom. If the stack is empty, print a message indicating that the stack is
empty. Otherwise, initialize a variable `current` with the value of `top`. While `current` is
not `None`, print the data of the current node and update `current` to point to the next
node. Print a newline character after printing all the items.
8. Define the `size` method in the `Stack` class. This method returns the number of items in
the stack. Initialize a variable `count` to 0 and `current` to `top`. While `current` is not
`None`, increment `count` by 1 and update `current` to point to the next node. Return
`count`.
9. Define the `peek` method in the `Stack` class. This method returns the top item from the
stack without removing it. If the stack is empty, print a message indicating that the stack
is empty and return `None`. Otherwise, return the data of the current `top` node.
10. Create an instance of the `Stack` class called `stack`.
11. Enter a `while True` loop to display the menu and perform stack operations until the user
chooses to exit.
12. Inside the loop, display the menu options: Push, Pop, Traverse, Number of nodes, Check
if stack is empty, Peek, and Exit.
13. Prompt the user to enter their choice.
14. Based on the user's choice, perform the corresponding operation:
o If the choice is 1 (Push), prompt the user to enter an item and call the `push` method
of the `stack` object to push the item onto the stack.
o If the choice is 2 (Pop), call the `pop` method of the `stack` object to remove and print
the top item from the stack.

37
o If the choice is 3 (Traverse), call the `display` method of the `stack` object to print the
items in the stack.
o If the choice is 4 (Number of nodes), call the `size` method of the `stack` object to get
the number of items in the stack and print it.
o If the choice is 5 (Check if stack is empty), call the `is_empty` method of the `stack`
object to check if the stack is empty and print the result.
o If the choice is 6 (Peek), call the `peek` method of the `stack` object to get the top item
from the stack without removing it and print it.
o If the choice is 7 (Exit), print a message indicating the program is exiting and break out
of the loop.
o If the choice is not a valid option, print an error message indicating an invalid choice.
15. Repeat the loop until the user chooses to exit.
16. End the program.

PROGRAM:

38
39
OUTPUT:

40
RESULT:
Thus, the python program to implement Stack and its operations using linked list is executed
successfully and output is verified.

41
Program 5.2: A Python program to implement Queue and its operations using linked list
AIM:
To write a Python program to implement Queue and its operations using linked list.
ALGORITHM:
1. Start the program
2. Define the `Node` class with attributes `data` and `next` to represent a single node in the
queue.
3. Define the `Queue` class with attributes `front`, `rear`, and `size` to represent the front
and rear nodes of the queue and the size of the queue, respectively.
4. Implement the `is_empty` method in the `Queue` class to check if the queue is empty. It
returns `True` if the front node is `None`, indicating an empty queue.
5. Implement the `enqueue` method in the `Queue` class to add an item to the rear of the
queue. It creates a new node with the given item and updates the `front` and `rear`
pointers accordingly. If the queue is initially empty, both `front` and `rear` will point to the
new node.
6. Implement the `dequeue` method in the `Queue` class to remove and return the item
from the front of the queue. It updates the `front` pointer to the next node and checks if
the queue becomes empty after the removal. If so, it updates the `rear` pointer to `None`
as well.
7. Implement the `display` method in the `Queue` class to print the items in the queue from
front to rear. It traverses the queue from the `front` node to the `rear` node, printing the
data of each node.
8. Implement the `get_size` method in the `Queue` class to return the number of nodes in
the queue. It simply returns the value of the `size` attribute.
9. Create an instance of the `Queue` class to work with the queue operations.
10. Enter a while loop to display the menu and process the user's choice until the user chooses
to quit.
11. Inside the loop, display the menu options to the user: enqueue, dequeue, display, number
of nodes, and quit.
12. Prompt the user for their choice and perform the corresponding operation based on the
input.
1. If the choice is 1 (enqueue), prompt the user for an item and call the `enqueue`
method to add the item to the queue.
2. If the choice is 2 (dequeue), call the `dequeue` method to remove and retrieve the
item from the front of the queue. Print the dequeued item if it exists.
3. If the choice is 3 (display), call the `display` method to print the items in the queue.
4. If the choice is 4 (number of nodes), call the `get_size` method to retrieve the number
of nodes in the queue and print it.
5. If the choice is 5 (quit), print a quitting message and break out of the loop.
6. If the choice is invalid, print an error message.
13. End the program.

42
PROGRAM:

43
OUTPUT:

44
RESULT:
Thus, the python program to implement Queue and its operations using linked list is
executed successfully and output is verified.

45
EXP 6: Applications of STACK
Program 6.1: A Python program to convert infix expression into postfix using stack
AIM:
To write a Python program to convert infix expression into postfix using stack.
ALGORITHM:
1. Start the program.
2. Define a function named `infix_to_postfix` that takes an infix expression as input.
3. Initialize a dictionary named `prec` to store operator precedence.
4. Create an empty stack named `op_stack` to store operators and an empty list named
`postfix_list` to store the postfix expression.
5. Tokenize the infix expression into a list of tokens.
6. Iterate over each token in the token list.
- If the current token is an operand (alphanumeric character), append it directly to
the `postfix_list`.
- If the current token is an opening parenthesis '(', push it onto the `op_stack`.
- If the current token is a closing parenthesis ')', pop operators from the stack and
append them to the `postfix_list` until an opening parenthesis '(' is encountered.
Discard both the opening and closing parentheses.
- If the current token is an operator, compare its precedence with the precedence
of the top operator on the stack. While the stack is not empty and the
precedence of the top operator is greater than or equal to the current operator,
pop the top operator from the stack and append it to the `postfix_list`. Then,
push the current operator onto the `op_stack`.
7. Repeat steps 6 for each token in the infix expression.
8. After scanning all tokens, pop any remaining operators from the `op_stack` and append
them to the `postfix_list`.
9. Join the tokens in the `postfix_list` with spaces to obtain the resulting postfix expression.
11. Return the postfix expression.
12. End the program.

46
PROGRAM:

OUTPUT:

RESULT:
Thus, the python program to convert an infix expression into postfix using a stack is executed
successfully and the output is verified.

47
Program 6.2: A Python program to evaluate postfix expression using stack
AIM:
To write a Python program to evaluate postfix expression using stack.
ALGORITHM:
1. Start the program.
2. Define a class named `Stack` with the following methods:
o `__init__()` method: Initialize an empty list to store items.
o `is_empty()` method: Check if the stack is empty.
o `push(item)` method: Push an item onto the stack.
o `pop()` method: Pop and return the top item from the stack.
o `peek()` method: Return the top item from the stack without removing it.
o `size()` method: Return the number of items in the stack.
3. Define a function named `postfix_eval` that takes a postfix expression as input.
o Function signature: `def postfix_eval(postfix_expr)`.
4. Initialize an empty stack object called `operand_stack` using the `Stack` class.
o Stack initialization: `operand_stack = Stack()`.
5. Tokenize the postfix expression into a list of tokens.
o Tokenization: `token_list = postfix_expr.split()`.
6. Iterate over each token in the token list.
o Loop over tokens: `for token in token_list:`.
7. If the current token is a digit, it is an operand. Convert it to an integer and push it onto
the `operand_stack`.
o Operand check: `if token.isdigit():`.
o Convert token to an integer: `operand = int(token)`.
o Push operand onto the `operand_stack`: `operand_stack.push(operand)`.
8. If the current token is an operator, pop the top two operands from the `operand_stack`.
o Operator check: `elif token in "+-*/":`.
o Pop the second operand: `operand2 = operand_stack.pop()`.
o Pop the first operand: `operand1 = operand_stack.pop()`.
o Perform the corresponding mathematical operation on the operands using the
`do_math` function and push the result back onto the `operand_stack`.
o Compute result: `result = do_math(token, operand1, operand2)`.
o Push result onto the `operand_stack`: `operand_stack.push(result)`.
9. After processing all tokens, the final result is the top value on the `operand_stack`. Pop
and return it as the output of the function.
o Return the top value from `operand_stack`: `return operand_stack.pop()`.
10. Define a function named `do_math` to perform arithmetic operations based on the
given operator.
o Function signature: `def do_math(operator, operand1, operand2)`.
o Depending on the operator, perform the corresponding mathematical operation
on the operands and return the result.
11. End the program.

48
PROGRAM:

49
OUTPUT:

RESULT:
Thus, the python program to evaluate postfix expression using stack is executed successfully
and the output is verified.

50

You might also like