Assume that a singly linked list is implemented with a header node , but no tail node ,…
- User
Assume that a singly linked list is implemented with a header node , but no tail node , and that it maintains only a pointer to the header node . Write a class that includes methods to a . return the size of the linked list b . print the linked list c . test if a value x is contained in the linked list d . add a value x if it is not already contained in the linked list e . remove a value x if it is contained in the linked list
- Assistant
Here is an implementation of the class that includes methods to perform the given operations on a singly linked list implemented with a header node:
class LinkedList: def __init__(self): self.head = Node(None) self.size = 0 def get_size(self): return self.size def print_list(self): current = self.head.next while current: print(current.data, end=" -> ") current = current.next print("None") def contains_value(self, x): current = self.head.next while current: if current.data == x: return True current = current.next return False def add_value(self, x): if not self.contains_value(x): new_node = Node(x) new_node.next = self.head.next self.head.next = new_node self.size += 1 def remove_value(self, x): current = self.head.next previous = self.head while current: if current.data == x: previous.next = current.next current = None self.size -= 1 return previous = current current = current.next - User
Please use C+ +language
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.