Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TickerNode:
- def __init__(self, headline):
- self.headline = headline
- self.next = None # initialize next pointer as null
- class CircularLinkedList:
- def __init__(self):
- self.head = None
- def find_headline(self, headline):
- if not self.head:
- print("The list is empty.")
- return
- current = self.head
- while True:
- if current.headline == headline:
- print("Headline found:", current.headline)
- return
- current = current.next
- if current == self.head:
- break
- print("Headline not found.")
- def add_in_order(self, new_node):
- if not self.head: # If the list is empty, initialize it with the new node
- self.head = new_node
- new_node.next = new_node # Point to itself to make it circular
- return
- current = self.head
- previous = None
- # Special case for inserting before the head node
- while True:
- if new_node.headline < self.head.headline:
- # Find the last node
- last_node = self.head
- while last_node.next != self.head:
- last_node = last_node.next
- new_node.next = self.head
- last_node.next = new_node
- self.head = new_node
- return
- # Iterate through the list to find the insertion point
- while current.next != self.head and current.headline < new_node.headline:
- previous = current
- current = current.next
- # Insertion point found
- if current.next == self.head and current.headline < new_node.headline:
- # Insert at the end of the list
- current.next = new_node
- new_node.next = self.head
- return
- previous.next = new_node
- new_node.next = current
- return
- # Example usage
- news_list = CircularLinkedList()
- # Adding nodes to the list
- news_list.add_in_order(TickerNode("Breaking News: Market Crash"))
- news_list.add_in_order(TickerNode("Latest Update: Weather Forecast"))
- news_list.add_in_order(TickerNode("Sports: Team Wins Championship"))
- news_list.add_in_order(TickerNode("Technology: New Smartphone Release"))
- # Searching for headlines
- news_list.find_headline("Latest Update: Weather Forecast") # Output: Headline found: Latest Update: Weather Forecast
- news_list.find_headline("Nonexistent Headline") # Output: Headline not found.
Advertisement
Add Comment
Please, Sign In to add comment