class Stack:
def __init__(self):
self.items = []
def push(self, item):
"""add an item to the top of the stack"""
self.items.append(item)
def pop(self):
"""Remove and return the top ite of the stack ."""
if not self.is_empty():
return self.items.pop()
else:
return None
def peek(self):
"""Return the top item of the stack without removing it."""
if not self.is_empty():
return self.items+[-1]
else:
return None
def is_empty(self):
"""check if the stack is empty ."""
return len(self.items) == 0
def search(self, item):
"""search for an item in the stack and return its index or -1 if not
found ."""
try:
return len(self.items) - 1 - self.items[::-1].index(item)
except ValueError:
return -1
def display(self):
"""Display the stack items ."""
return self.items[:: -1]
def search_element(array,element):
"""Search for an element in the array and
return its index or a not found message."""
if element in array:
return array.index(element)
else:
return -1
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
"""Add an item to the end of the queue."""
self.items.append(item)
def dequeue(self):
"""Remove and return the front item of the queue. """
if not self.is_empty():
return self.items.pop(0)
return None
def is_empty(self):
"""check if the queue is empty."""
return len(self.items) == 0
def display(self):
"""display the queue items.1"""
return self.items
class Node:
"""Class to represent a node in the linked list .
"""
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None # Initialize the head of the linked list
def append(self, data):
"""Add a new node at the end of the linked list."""
new_node = Node(data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def delete(self, key):
"""Delete the first node with the specified data."""
temp = self.head
if temp and temp.data == key:
self.head = temp.next
temp = None
return
prev = None
while temp and temp.data != key:
prev = temp
temp = temp.next
if temp is None:
return
prev.next = temp.next
temp = None
def display(self):
"""Display the linked list items."""
elements = []
current = self.head
while current:
elements.append(current.data)
current = current.next
return elements
def main():
while True:
print("Data structure are divided into two part ")
print("1== linear Data str")
print("2== None linear Data str")
print("3 == Exit")
choice = input("Please select a number : ")
if choice == "1":
while True:
print("Linear Data str is that str that data is locate in a row or
locate in a colum,"
" and every data have one child or one brunch")
print("and it has four type:")
print(" Array")
print("Stack")
print("Linked list")
print("Queue")
print("5 == Go to main menu")
linear_choice = input("please select one of the number of linear
algorithm..:").strip().lower()
if linear_choice == "array".strip().lower():
print("Array is a collection of elements by the standard size
that stored finitely in memory")
size = int(input("Please select the none room of array :"))
array = [None] * size
print(f"{size} room of None arrays is created")
for i in range(size):
data = input(f"please dial {i+1} of attributes for arrays")
array[i] = data
print("your array is here...!!")
print(array)
sorted_array = sorted(array)
print("this array after sorted is :", sorted_array)
while True:
action = input("Do you want to (a)dd, (d)elet, or (s)earch
an element or (n)othing???? (a/b/n/s):").lower()
if action == "a":
new_element = input("Enter the new element that you
want to add :")
array.append(new_element)
array.sort()
print('Updated array is :',array)
elif action == "d":
delete_element = input("Enter the element that you want
to delete it : ")
if delete_element in array:
array.remove(delete_element)
print(f"{delete_element} has been removed!!!")
else:
print(f"{delete_element} is not found in this array
!!!")
print("Updated array is :", array)
elif action == "s":
element_to_search = input("Enter the element you want
to search for :")
index = search_element(array,element_to_search)
if index != -1:
print(f"{element_to_search} found at index
{index}th.")
else:
print(f"{element_to_search}not found in this
array.")
elif action == "n":
print("your final array is:", array)
break
else:
print("Invalid between (a), (d) , (n) and (s)")
elif linear_choice == "stack":
print("stack is a type of linear data structure..")
stack = Stack()
stack_size = int(input("Enter the number of elements in the
stack :"))
for i in range(stack_size):
element = input(f"Enter element {i +1 }th for the stack")
stack.push(element)
print("You have entered the following stack :")
print(stack.display())
while True:
action = input("Do you want to (push) , (pop) , (search) ,
(display) , or (nothing) .?").strip().lower()
if action == "push":
new_element = input("Enter the element you want to
push:")
stack.push(new_element)
print(f'{new_element} has been pushed onto the
stack .')
elif action == "pop":
poped_element = input("Enter the element you want to
push :")
stack.pop()
if poped_element is not None:
print(f'{poped_element} has been popped from the
stack .')
else:
print("Stack is empty. or Nothing to pop..")
elif action == "search":
element_to_search = input(""
"Enter the element you want
to search for :")
index = stack.search(element_to_search)
if index != -1:
print(f"{element_to_search} found at index {index}.
")
else:
print(f"{element_to_search} not found in the
stack.")
elif action == "display":
print("current stack :", stack.display())
elif action == "Nothing ".lower().strip():
print('No changes made, and your final stack
is :',stack.display())
break
else:
print("invalid option. Please select (push), (Pop),
(search), (display) or (NOthing ) options")
elif linear_choice =='queue'.strip().lower():
queue = Queue()
queue_size = int(input(f"Enter the number of elements in the
queue: "))
for y in range(queue_size):
element = input(f"Enter element {y +1}th for queue!")
queue.enqueue(element)
print("You have entered the following queue:")
print(queue.display())
while True:
action = input("Do you want to (e)nqueue, (d)equeue,
(v)iew, or (n)othing?..(e/d/v/n)").lower()
if action == "e":
new_element = input("enter th element you want to
enqueue: ")
queue.enqueue(new_element)
print(f"{new_element} has been added to the queue.")
elif action == "d":
dequeue_element = queue.dequeue()
if dequeue_element is not None:
print(f"{dequeue_element} has been removed from the
queue")
else:
pr1int("Queue is empty, Nothing to dequeue")
elif action == "v":
print("Current queue:", queue.display())
elif action == "n":
print("NO change made !")
print(queue.display())
break
else:
print("Invalid option , Please select (e), (d), (v), 0r
(n).")
elif linear_choice == "linked list".lower().strip():
linked_list = LinkedList() # Create a new LinkedList instance
# Taking linked list size from user
list_size = int(input("Enter the number of elements in the
linked list: "))
# Taking linked list elements from user
for i in range(list_size):
element = input(f"Enter element {i + 1}: ")
linked_list.append(element)
print("You have entered the following linked list:")
print(linked_list.display()) # Display the linked list after
input
while True:
action = input("Do you want to (a)ppend, (d)elete, (v)iew,
or (n)othing? (a/d/v/n): ").lower()
if action == 'a':
new_element = input("Enter the element you want to
append: ")
linked_list.append(new_element)
print(f"{new_element} has been added to the linked
list.")
elif action == 'd':
delete_element = input("Enter the element you want to
delete: ")
linked_list.delete(delete_element)
print(f"{delete_element} has been removed from the
linked list.")
elif action == 'v':
print("Current linked list:", linked_list.display())
elif action == 'n':
print("No changes made.")
break
else:
print("Invalid option. Please select (a), (d), (v), or
(n).")
elif linear_choice == "5":
break
else:
print("invalid correct syntax, please select from 1 up to 4....")
elif choice == "2":
print("None Linear Data str is that str that ever data have more than
one child or brunch")
print("It has three type")
print("1 = Tree")
print("2 = Graph")
print("3 = Hash table")
elif choice == "3":
print("Exit the program")
break
else:
print("Error...!!!, please select option 1 or 2 ")
if __name__== "__main__":
main()