Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
5003CEM_Tasks/STD_5 - Linked List.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
57 lines (47 sloc)
1.72 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, dataval = None): | |
self.dataval = dataval | |
self.nextval = None | |
class SLinkedList: | |
def __init__(self): | |
self.headval = None | |
def listprint(self): | |
printval = self.headval | |
while printval is not None: | |
print(printval.dataval) | |
printval = printval.nextval | |
def AtBeginning(self,newdata): | |
NewNode = Node(newdata) | |
def AtEnd(self, newdata): | |
NewNode = Node(newdata) | |
if self.headval is None: | |
self.headval = NewNode | |
return | |
last = self.headval | |
while(last.nextval): | |
last = last.nextval | |
last.nextval = NewNode | |
def Insert(self,val_before,newdata): | |
if val_before is None: | |
print("No node to insert after") | |
return | |
#v v v v v v v v v v v v v v v v v v v v v v v v v v v v v v v v v | |
else: #if the previous value exists | |
newdata.nextval = val_before.nextval #new entry is created and location is set as before the entry in front of it | |
val_before.nextval = newdata #previous value in that location is swapped with the new entry | |
#^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ | |
list = SLinkedList() | |
list.headval = Node("Mon") | |
e2 = Node("Tue") | |
e3 = Node("Thur") | |
e4 = Node("Fri") | |
e5 = Node("Sat") | |
list.headval.nextval = e2 | |
e2.nextval = e3 | |
e3.nextval = e4 | |
e4.nextval = e5 | |
list.AtEnd("Sun") | |
#v v v v v v v v v v v v v v v v v v v v v v v v v v v v v v v v v | |
list.Insert(e2,Node("Wed")) #add new entry to the list at the position e2 | |
#^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ | |
list.listprint() |