Add Python doctests to singly linked list (#190)

pull/194/head
Christian Clauss 2021-04-14 20:37:20 +02:00 committed by GitHub
parent 0ca911387b
commit d991c37cf1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 86 additions and 54 deletions

View File

@ -1,58 +1,90 @@
# A simple Python program to create a singly linked list # Create a singly linked list
# Node class class Node:
class Node: def __init__(self, data):
self.data = data
# Function to initialise the node object self.next = None
def __init__(self, data):
self.data = data # Assign data def __repr__(self):
self.next = None # Initialize next as null """
>>> Node(77)
Node(77)
# Linked List class contains a Node object """
class LinkedList: return f"Node({self.data})"
# Function to initialize head
def __init__(self): class LinkedList:
def __init__(self):
self.head = None self.head = None
def __iter__(self):
# Function to insert a new node at the beginning """
def insertAtHead(self, new_data): >>> ll = LinkedList()
>>> list(ll)
# 1 & 2: Allocate the Node & []
# Put in the data >>> ll.push(88)
new_node = Node(new_data) >>> tuple(ll)
(88,)
# 3. Make next of new Node as head >>> ll.push(89)
new_node.next = self.head >>> tuple(ll)
(89, 88)
# 4. Move the head to point to new Node """
self.head = new_node node = self.head
def removeAtHead(self): while node:
temp = self.head yield node.data # `yield node` would also be possible
node = node.next
# If head node itself holds the key to be deleted
if (temp is not None):
self.head = temp.next
temp = None
return
else:
return('underflow')
def printList(self):
temp = self.head
while(temp):
print (temp.data)
temp = temp.next
def __len__(self):
return len(tuple(iter(self)))
# Code execution starts here
if __name__=='__main__':
l=LinkedList()
l.insertAtHead(1)
l.insertAtHead('xyz')
l.insertAtHead(1.1)
l.removeAtHead()
l.printList()
def __repr__(self):
"""
>>> ll = LinkedList()
>>> repr(ll)
'LinkedList()'
>>> ll.push(99)
>>> ll.push(100)
>>> repr(ll)
'LinkedList(100, 99)'
>>> str(ll)
'LinkedList(100, 99)'
"""
return f"LinkedList({', '.join(str(node) for node in self)})"
def push(self, data):
node = Node(data)
node.next = self.head
self.head = node
def pop(self):
"""
>>> ll = LinkedList()
>>> len(ll)
0
>>> ll.push("push/pop")
>>> len(ll)
1
>>> ll.pop()
'push/pop'
>>> len(ll)
0
>>> ll.pop()
Traceback (most recent call last):
...
IndexError: pop from empty LinkedList
"""
node = self.head
if not node:
raise IndexError("pop from empty LinkedList")
self.head = node.next
return node.data
if __name__ == '__main__':
ll = LinkedList()
ll.push(1)
ll.push('xyz')
ll.push(1.1)
ll.pop()
print(ll)
print(list(ll))