linked_list

py

School

University Of Arizona *

*We aren’t endorsed by this school

Course

120

Subject

Computer Science

Date

Apr 3, 2024

Type

py

Pages

3

Uploaded by MateClover22302

Report
''' File: linked_list.py Author: Nick Brobeck Course: CSC 120, Spring Semester Purpose: Provides a linked list implementation. It's used for storing collections of nodes efficiently. Simple yet powerful for managing lists. ''' class LinkedListIterator: """ Iterator for the LinkedList class. Attributes: current: The current node in the iteration. """ def __init__(self, head): """ Initializes the iterator with the head of the LinkedList. Parameters: head: The starting node for iteration. """ self.current = head def __iter__(self): """ Returns the iterator object itself. Returns: LinkedListIterator: The iterator for the LinkedList. """ return self def __next__(self): """ Moves to the next node in the LinkedList and returns its name. Returns: str: The name of the current Node. Raises: StopIteration: If there are no more nodes in the list. """ if self.current: name = self.current.name self.current = self.current.next return name else: raise StopIteration class Node: """ A node in the LinkedList representing a person. Attributes: name: A string representing the name of the person. friends: A LinkedList representing friends of the person. next: The next Node in the LinkedList. """
def __init__(self, name): """ Initializes a new Node. Parameters: name: A string representing the name of the person. """ self.name = name self.friends = LinkedList() self.next = None class LinkedList: """ A LinkedList implementation for storing a collection of Nodes. """ def __init__(self): """ Initializes a new, empty LinkedList. """ self.head = None def add(self, name): """ Adds a new Node with the given name to the end of the LinkedList. Parameters: name: The name to be added to the list. """ new_node = Node(name) if not self.head: self.head = new_node else: current = self.head while current.next: current = current.next current.next = new_node def find(self, name): """ Finds and returns the Node with the given name. Parameters: name: A string representing the name of the Node to find. Returns: Node: The found Node, or None if no Node with the name exists. """ current = self.head while current: if current.name == name: return current current = current.next return None def __iter__(self): """
Returns an iterator for the LinkedList. Returns: LinkedListIterator: An iterator for the LinkedList. """ return LinkedListIterator(self.head) def add_friendship(node_1, node_2): """ Creates a mutual friendship between two Nodes. Parameters: node_1: The first Node. node_2: The second Node. """ node_1.friends.add(node_2.name) node_2.friends.add(node_1.name)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help