DoublyLinkedList.__iter__() (#168)

pull/173/head
Christian Clauss 2021-04-11 23:49:05 +02:00 committed by GitHub
parent c245d22869
commit 8dd686a31c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 34 additions and 28 deletions

View File

@ -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})"
class DoublyLinkedList:
def __init__(self): def __init__(self):
self.head = None self.head = None
# Adding data elements def __iter__(self):
def push(self, NewVal): node = self.head
NewNode = Node(NewVal) while node:
NewNode.next = self.head yield node.data
if self.head is not None:
self.head.prev = NewNode
self.head = NewNode
# Print the Doubly Linked list
def listprint(self, node):
while (node is not None):
print(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]