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