File tree 1 file changed +56
-0
lines changed
Filter options
1 file changed +56
-0
lines changed
Original file line number Diff line number Diff line change
1
+ # A complete working Python program to find length of a
2
+ # Linked List iteratively
3
+
4
+ # Node class
5
+ class Node :
6
+ # Function to initialise the node object
7
+ def __init__ (self , data ):
8
+ self .data = data # Assign data
9
+ self .next = None # Initialize next as null
10
+
11
+
12
+ # Linked List class contains a Node object
13
+ class LinkedList :
14
+
15
+ # Function to initialize head
16
+ def __init__ (self ):
17
+ self .head = None
18
+
19
+
20
+ # This function is in LinkedList class. It inserts
21
+ # a new node at the beginning of Linked List.
22
+ def push (self , new_data ):
23
+
24
+ # 1 & 2: Allocate the Node &
25
+ # Put in the data
26
+ new_node = Node (new_data )
27
+
28
+ # 3. Make next of new Node as head
29
+ new_node .next = self .head
30
+
31
+ # 4. Move the head to point to new Node
32
+ self .head = new_node
33
+
34
+
35
+ # This function counts number of nodes in Linked List
36
+ # iteratively, given 'node' as starting node.
37
+ def getCount (self ):
38
+ temp = self .head # Initialise temp
39
+ count = 0 # Initialise count
40
+
41
+ # Loop while end of linked list is not reached
42
+ while (temp ):
43
+ count += 1
44
+ temp = temp .next
45
+ return count
46
+
47
+
48
+ # Code execution starts here
49
+ if __name__ == '__main__' :
50
+ llist = LinkedList ()
51
+ llist .push (1 )
52
+ llist .push (3 )
53
+ llist .push (1 )
54
+ llist .push (2 )
55
+ llist .push (1 )
56
+ print ("Count of nodes is :" ,llist .getCount ())
You can’t perform that action at this time.
0 commit comments