|
| 1 | +# The program that creates a single link list of true values |
| 2 | +# and implements the actions outlined in the link list. |
| 3 | + |
| 4 | +class LinkedList: |
| 5 | + class ListNode: |
| 6 | + def __init__(self, data, next= None): |
| 7 | + self.info = data |
| 8 | + self.next = next |
| 9 | + |
| 10 | + def getInfo(self): |
| 11 | + return self.info |
| 12 | + |
| 13 | + def setInfo(self, value): |
| 14 | + self.info = value |
| 15 | + |
| 16 | + def getNext(self): |
| 17 | + return self.next |
| 18 | + |
| 19 | + def setNext(self, ptr): |
| 20 | + self.next = ptr #end of listNode class |
| 21 | + |
| 22 | + def __init__(self): |
| 23 | + self.head = None |
| 24 | + self.last = None |
| 25 | + self.size = 0 |
| 26 | + |
| 27 | + def __del__(self): |
| 28 | + current = self.head |
| 29 | + while current: |
| 30 | + ptr = current |
| 31 | + current = current.next |
| 32 | + del ptr |
| 33 | + |
| 34 | + def getSize(self): |
| 35 | + return self.size |
| 36 | + def isEmpty(self): |
| 37 | + return self.head == None |
| 38 | + |
| 39 | +#Search Node |
| 40 | + |
| 41 | + def searchNode(self, data): |
| 42 | + if (self.isEmpty()): |
| 43 | + return None |
| 44 | + else: |
| 45 | + ptr = self.head |
| 46 | + found = False |
| 47 | + while ptr and found is False: |
| 48 | + if ptr.getInfo() == data: |
| 49 | + found == True |
| 50 | + else: |
| 51 | + ptr == ptr.getNext() |
| 52 | + return ptr |
| 53 | + |
| 54 | + def insertAtFirst(self, ptr): |
| 55 | + self.head = ptr |
| 56 | + self.size += 1 |
| 57 | + if self.getSize() == 1: |
| 58 | + self.last = self.head |
| 59 | + return True |
| 60 | + |
| 61 | + def insertAfterNode(self, ptr): |
| 62 | + if (self.isEmpty()): |
| 63 | + self.head = self.last = ptr |
| 64 | + else: |
| 65 | + self.last.next = ptr |
| 66 | + self.last = ptr |
| 67 | + self.size += 1 |
| 68 | + |
| 69 | + def deleteNode(self, data): |
| 70 | + current = self.head |
| 71 | + pre = None |
| 72 | + found = False |
| 73 | + while current and found is False: |
| 74 | + if current.getInfo() == data: |
| 75 | + found = True |
| 76 | + else: |
| 77 | + pre = current |
| 78 | + current = current.getNext() |
| 79 | + if found: |
| 80 | + if current == self.head: #first Node deleted |
| 81 | + self.head = current.next |
| 82 | + del current |
| 83 | + else: |
| 84 | + pre.next = current.next |
| 85 | + current.next = None |
| 86 | + del current #current = None |
| 87 | + self.size -= 1 |
| 88 | + return found |
| 89 | + |
| 90 | + def traverse(self): |
| 91 | + if (self.isEmpty() != True): |
| 92 | + ptr = self.head |
| 93 | + while ptr: |
| 94 | + print(ptr.info, end = "\n") |
| 95 | + ptr = ptr.getNext() |
| 96 | + |
| 97 | + |
0 commit comments