DoublyLinkedList.__iter__() (#168)
parent
c245d22869
commit
8dd686a31c
|
@ -1,34 +1,40 @@
|
||||||
# A simple Python program to create a linked list
|
|
||||||
|
|
||||||
# Node class
|
|
||||||
class Node:
|
class Node:
|
||||||
def __init__(self, data):
|
def __init__(self, data):
|
||||||
self.data = data
|
self.data = data
|
||||||
self.next = None
|
self.next = None
|
||||||
self.prev = None
|
self.prev = None
|
||||||
|
|
||||||
class doubly_linked_list:
|
def __repr__(self):
|
||||||
|
return f"Node({self.data})"
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self.head = None
|
|
||||||
|
|
||||||
# Adding data elements
|
class DoublyLinkedList:
|
||||||
def push(self, NewVal):
|
def __init__(self):
|
||||||
NewNode = Node(NewVal)
|
self.head = None
|
||||||
NewNode.next = self.head
|
|
||||||
if self.head is not None:
|
|
||||||
self.head.prev = NewNode
|
|
||||||
self.head = NewNode
|
|
||||||
|
|
||||||
# Print the Doubly Linked list
|
def __iter__(self):
|
||||||
def listprint(self, node):
|
node = self.head
|
||||||
while (node is not None):
|
while node:
|
||||||
print(node.data),
|
yield node.data
|
||||||
last = node
|
node = node.next
|
||||||
node = node.next
|
|
||||||
|
|
||||||
dllist = doubly_linked_list()
|
def __repr__(self):
|
||||||
dllist.push(12)
|
return f"DoublyLinkedList({', '.join(str(node) for node in self)})"
|
||||||
dllist.push(8)
|
|
||||||
dllist.push(62)
|
# Adding data elements is like pushing onto a stack
|
||||||
dllist.listprint(dllist.head)
|
def push(self, data):
|
||||||
|
node = Node(data)
|
||||||
|
node.next = self.head
|
||||||
|
if self.head:
|
||||||
|
self.head.prev = node
|
||||||
|
self.head = node
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
dllist = DoublyLinkedList()
|
||||||
|
for i in 12, 8, 62:
|
||||||
|
dllist.push(i)
|
||||||
|
print(dllist) # DoublyLinkedList(62, 8, 12)
|
||||||
|
print(list(dllist)) # [62, 8, 12]
|
||||||
|
print(list(reversed(list(dllist)))) # [12, 8, 62]
|
||||||
|
print(sorted(dllist)) # [8, 12, 62]
|
||||||
|
|
Loading…
Reference in New Issue