Skip to content

Instantly share code, notes, and snippets.

@danielz02
Created July 25, 2020 11:28
Show Gist options
  • Select an option

  • Save danielz02/5b5b0cbb736624e7726bb8afef92115a to your computer and use it in GitHub Desktop.

Select an option

Save danielz02/5b5b0cbb736624e7726bb8afef92115a to your computer and use it in GitHub Desktop.
Linked List Traversal
# A simple Python program for traversal of a linked list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class contains a Node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# This function prints contents of linked list
# starting from head
def printList(self):
temp = self.head
while (temp):
print (temp.data)
temp = temp.next
def count_node(self):
return self.__count_node(self.head)
def __count_node(self, current):
if current == None:
return 0
else:
return 1 + self.__count_node(current.next)
# Code execution starts here
if __name__=='__main__':
# Start with the empty list
llist = LinkedList()
llist.head = Node(1)
second = Node(2)
third = Node(3)
llist.head.next = second; # Link first node with second
second.next = third; # Link second node with the third node
# llist.printList()
print(llist.count_node())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment