| 4 | self.next = None |
| 5 | |
| 6 | class CircularLinkedList: |
| 7 | def __init__(self): |
| 8 | self.last = None |
| 9 | |
| 10 | def addToEmpty(self, data): |
| 11 | |
| 12 | if self.last != None: |
| 13 | return self.last |
| 14 | |
| 15 | # allocate memory to the new node and add data to the node |
| 16 | newNode = Node(data) |
| 17 | |
| 18 | # assign last to newNode |
| 19 | self.last = newNode |
| 20 | |
| 21 | # create link to iteself |
| 22 | self.last.next = self.last |
| 23 | return self.last |
| 24 | |
| 25 | def addFront(self, data): |
| 26 | |
| 27 | # check if the list is empty |
| 28 | if self.last == None: |
| 29 | return self.addToEmpty(data) |
| 30 | |
| 31 | # allocate memory to the new node and add data to the node |
| 32 | newNode = Node(data) |
| 33 | |
| 34 | # store the address of the current first node in the newNode |
| 35 | newNode.next = self.last.next |
| 36 | |
| 37 | # make newNode as last |
| 38 | self.last.next = newNode |
| 39 | |
| 40 | return self.last |
| 41 | |
| 42 | def addEnd(self, data): |
| 43 | # check if the node is empty |
| 44 | if self.last == None: |
| 45 | return self.addToEmpty(data) |
| 46 | |
| 47 | # allocate memory to the new node and add data to the node |
| 48 | newNode = Node(data) |
| 49 | |
| 50 | # store the address of the last node to next of newNode |
| 51 | newNode.next = self.last.next |
| 52 | |
| 53 | # point the current last node to the newNode |
| 54 | self.last.next = newNode |
| 55 | |
| 56 | # make newNode as the last node |
| 57 | self.last = newNode |
| 58 | |
| 59 | return self.last |
| 60 | |
| 61 | def addAfter(self, data, item): |
| 62 | |
| 63 | # check if the list is empty |