| 2 | |
| 3 | |
| 4 | class LinkedList(object): |
| 5 | def __init__(self): |
| 6 | self.head_ = None |
| 7 | |
| 8 | def set_head(self, head_node): |
| 9 | self.head_ = head_node |
| 10 | |
| 11 | def __len__(self): |
| 12 | count = 0 |
| 13 | current = self.head_ |
| 14 | while current: |
| 15 | count += 1 |
| 16 | current = current.get_next() |
| 17 | return count |
| 18 | |
| 19 | def __str__(self): |
| 20 | current = self.head_ |
| 21 | output = "" |
| 22 | while current: |
| 23 | output += str(current) + " -> " |
| 24 | current = current.get_next() |
| 25 | return output |
| 26 | |
| 27 | # Pops an item from the front of the list |
| 28 | def pop(self): |
| 29 | if self.head_: |
| 30 | self.head_ = self.head_.get_next() |
| 31 | else: |
| 32 | raise IndexError("Unable to pop from empty list") |
| 33 | |
| 34 | # Returns true if list contains the given value. |
| 35 | def contains(self, value): |
| 36 | found = False |
| 37 | current = self.head_ |
| 38 | while current and not found: |
| 39 | if current.get_data() == value: |
| 40 | found = True |
| 41 | else: |
| 42 | current = current.get_next() |
| 43 | return found |
| 44 | |
| 45 | # Deletes all instances of given value in list. |
| 46 | def delete(self, value): |
| 47 | current = self.head_ |
| 48 | prev = None |
| 49 | while current: |
| 50 | if current.get_data() == value: |
| 51 | if prev: |
| 52 | prev.set_next(current.get_next()) |
| 53 | else: |
| 54 | self.head_ = current.get_next() |
| 55 | else |
| 56 | prev = current |
| 57 | current = current.get_next() |
| 58 | |
| 59 | # Pushes an item on the front of the list. |
| 60 | def push(self, value): |
| 61 | node = Node(value) |