Certainly! Let's consider an example illustrating the use of a non-primitive data structure. In this case, I'll use a Python list (which is a dynamic array) to implement a simple stack. A stack is a non-primitive data structure commonly used in programming for Last In, First Out (LIFO) operations.
# Example: Implementing a Stack using a Non-Primitive Data Structure (List)
class Stack:
def __init__(self):
# Using a non-primitive data structure (list) to store stack elements
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
# Using a non-primitive operation (append) to add an item to the stack
self.items.append(item)
def pop(self):
if not self.is_empty():
# Using a non-primitive operation (pop) to remove and return the top item from the stack
return self.items.pop()
else:
return "Stack is empty"
def peek(self):
if not self.is_empty():
# Using a non-primitive operation (indexing) to retrieve the top item from the stack without removing it
return self.items[-1]
else:
return "Stack is empty"
def size(self):
# Using a non-primitive operation (len) to get the size of the stack
return len(self.items)
# Creating a stack
stack = Stack()
# Pushing elements onto the stack
stack.push(10)
stack.push(20)
stack.push(30)
# Peeking at the top element
print("Top element:", stack.peek())
# Popping elements from the stack
print("Popped:", stack.pop())
print("Popped:", stack.pop())
# Checking if the stack is empty
print("Is the stack empty?", stack.is_empty())
# Checking the size of the stack
print("Size of the stack:", stack.size())
In this example:
-
Non-Primitive Data Structure Used:
- The non-primitive data structure used is a list (self.items) to implement a stack.
-
Operations:
- Non-primitive operations such as append (to push), pop (to pop), and indexing (to peek) are used to manipulate the stack.
-
Functionality:
- The Stack class provides typical stack operations: push, pop, peek, checking if the stack is empty, and getting the size of the stack.
-
Usage:
- The stack is created, elements are pushed onto it, and then operations like peeking, popping, checking emptiness, and getting the size are performed.
This example illustrates the use of a non-primitive data structure (list) to implement a basic stack, showcasing how non-primitive structures enable the creation of more complex and specialized data structures for solving specific problems.