मान लीजिए हमारे पास एक सिंगली लिंक्ड लिस्ट है, हमें इसकी लंबाई ढूंढनी है। लिंक्ड लिस्ट में next और val फील्ड हैं।
उदाहरण के लिए, यदि इनपुट है [2 -> 4 -> 5 -> 7 -> 8 -> 9 -> 3], तो आउटपुट होगा 7।
हल करने के चरण
count := 0- जब तक
nodeनल नहीं है:count := count + 1node := node का next
countलौटाएं।
उदाहरण
class ListNode:
def __init__(self, data, next=None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
class Solution:
def solve(self, node):
count = 0
while node:
count += 1
node = node.next
return count
ob = Solution()
head = make_list([2,4,5,7,8,9,3])
print(ob.solve(head))
इनपुट
[2,4,5,7,8,9,3]
आउटपुट
7