|
| 1 | +# The program that creates a single link list of true values |
| 2 | +# and implements the actions outlined in the link list. |
| 3 | + |
| 4 | +classLinkedList: |
| 5 | +classListNode: |
| 6 | +def__init__(self,data,next=None): |
| 7 | +self.info=data |
| 8 | +self.next=next |
| 9 | + |
| 10 | +defgetInfo(self): |
| 11 | +returnself.info |
| 12 | + |
| 13 | +defsetInfo(self,value): |
| 14 | +self.info=value |
| 15 | + |
| 16 | +defgetNext(self): |
| 17 | +returnself.next |
| 18 | + |
| 19 | +defsetNext(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 | +whilecurrent: |
| 30 | +ptr=current |
| 31 | +current=current.next |
| 32 | +delptr |
| 33 | + |
| 34 | +defgetSize(self): |
| 35 | +returnself.size |
| 36 | +defisEmpty(self): |
| 37 | +returnself.head==None |
| 38 | + |
| 39 | +#Search Node |
| 40 | + |
| 41 | +defsearchNode(self,data): |
| 42 | +if (self.isEmpty()): |
| 43 | +returnNone |
| 44 | +else: |
| 45 | +ptr=self.head |
| 46 | +found=False |
| 47 | +whileptrandfoundisFalse: |
| 48 | +ifptr.getInfo()==data: |
| 49 | +found==True |
| 50 | +else: |
| 51 | +ptr==ptr.getNext() |
| 52 | +returnptr |
| 53 | + |
| 54 | +definsertAtFirst(self,ptr): |
| 55 | +self.head=ptr |
| 56 | +self.size+=1 |
| 57 | +ifself.getSize()==1: |
| 58 | +self.last=self.head |
| 59 | +returnTrue |
| 60 | + |
| 61 | +definsertAfterNode(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 | +defdeleteNode(self,data): |
| 70 | +current=self.head |
| 71 | +pre=None |
| 72 | +found=False |
| 73 | +whilecurrentandfoundisFalse: |
| 74 | +ifcurrent.getInfo()==data: |
| 75 | +found=True |
| 76 | +else: |
| 77 | +pre=current |
| 78 | +current=current.getNext() |
| 79 | +iffound: |
| 80 | +ifcurrent==self.head:#first Node deleted |
| 81 | +self.head=current.next |
| 82 | +delcurrent |
| 83 | +else: |
| 84 | +pre.next=current.next |
| 85 | +current.next=None |
| 86 | +delcurrent#current = None |
| 87 | +self.size-=1 |
| 88 | +returnfound |
| 89 | + |
| 90 | +deftraverse(self): |
| 91 | +if (self.isEmpty()!=True): |
| 92 | +ptr=self.head |
| 93 | +whileptr: |
| 94 | +print(ptr.info,end="\n") |
| 95 | +ptr=ptr.getNext() |
| 96 | + |
| 97 | + |