{"id":26868,"date":"2017-12-26T20:41:26","date_gmt":"2017-12-26T15:11:26","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26868"},"modified":"2018-10-30T16:17:30","modified_gmt":"2018-10-30T10:47:30","slug":"python-algorithm-find-length-linked-list-iterative-recursive","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-algorithm-find-length-linked-list-iterative-recursive\/","title":{"rendered":"Find Length of a Linked List both Iterative and Recursive"},"content":{"rendered":"<h3 id=\"find-length-of-a-linked-list-both-iterative-and-recursive\"><span style=\"color: #003366;\">Find Length of a Linked List both Iterative and Recursive:<\/span><\/h3>\n<p>Write a <a href=\"https:\/\/www.wikitechy.com\/tutorials\/python\/python-operator\" target=\"_blank\" rel=\"noopener\">Python function<\/a> to count number of nodes in a given singly linked list.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"alignleft size-full wp-image-26889\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_find_length.png\" alt=\"C Algorithm - Find Length of a Linked List both Iterative and Recursive\" width=\"878\" height=\"184\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_find_length.png 878w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_find_length-300x63.png 300w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Linkedlist_find_length-768x161.png 768w\" sizes=\"(max-width: 878px) 100vw, 878px\" \/><\/p>\n<p>For example, the function should return 5 for linked list 1-&gt;3-&gt;1-&gt;2-&gt;1.<\/p>\n<h3 id=\"singly-linked-list\"><span style=\"color: #993366;\">Singly Linked List:<\/span><\/h3>\n<p>Singly Linked List is a collection of <strong>ordered set of elements<\/strong>. A Node in singly linked list has two parts \u2013 <strong>data part and link part<\/strong>. Data part of the node contains the actual information which is represented as node. Link part of the node contains address of next node linked to it.<\/p>\n<p>It can be traversed in only one direction because the node stores only next pointer. So, it can\u2019t\u00a0<a href=\"https:\/\/www.wikitechy.com\/technology\/python-algorithm-write-function-reverse-linked-list\/\" target=\"_blank\" rel=\"noopener\">reverse linked list.<\/a><\/p>\n<h3 id=\"iterative-solution\"><span style=\"color: #333399;\"><strong>Iterative Solution<\/strong><\/span><\/h3>\n<pre>1) Initialize count as 0 \r\n2) Initialize a node pointer, current = head.\r\n3) Do following while current is not NULL\r\n     a) current = current -&gt; next\r\n     b) count++;\r\n4) Return count<\/pre>\n<h3 id=\"python-programming\"><span style=\"color: #ff0000;\"><strong>Python Programming:<\/strong><\/span><\/h3>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># A complete working Python program to find length of a<br\/># Linked List iteratively<br\/> <br\/># Node class<br\/>class Node:<br\/>    # Function to initialise the node object<br\/>    def __init__(self, data):<br\/>        self.data = data # Assign data<br\/>        self.next = None # Initialize next as null<br\/> <br\/> <br\/># Linked List class contains a Node object<br\/>class LinkedList:<br\/> <br\/>    # Function to initialize head<br\/>    def __init__(self):<br\/>        self.head = None<br\/> <br\/> <br\/>    # This function is in LinkedList class. It inserts<br\/>    # a new node at the beginning of Linked List.<br\/>    def push(self, new_data):<br\/> <br\/>        # 1 &amp; 2: Allocate the Node &amp;<br\/>        #     Put in the data<br\/>        new_node = Node(new_data)<br\/> <br\/>        # 3. Make next of new Node as head<br\/>        new_node.next = self.head<br\/> <br\/>        # 4. Move the head to point to new Node<br\/>        self.head = new_node<br\/> <br\/> <br\/>    # This function counts number of nodes in Linked List<br\/>    # iteratively, given &#039;node&#039; as starting node.<br\/>    def getCount(self):<br\/>        temp = self.head # Initialise temp<br\/>        count = 0 # Initialise count<br\/> <br\/>        # Loop while end of linked list is not reached<br\/>        while (temp):<br\/>            count += 1<br\/>            temp = temp.next<br\/>        return count<br\/> <br\/> <br\/># Code execution starts here<br\/>if __name__==&#039;__main__&#039;:<br\/>    llist = LinkedList()<br\/>    llist.push(1)<br\/>    llist.push(3)<br\/>    llist.push(1)<br\/>    llist.push(2)<br\/>    llist.push(1)<br\/>    print &#039;Count of nodes is :&#039;,llist.getCount()<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<h3 id=\"output\"><span style=\"color: #339966;\"><strong>Output:<\/strong><\/span><\/h3>\n<pre>count of nodes is 5<\/pre>\n<h3 id=\"recursive-solution\"><span style=\"color: #333399;\"><strong>Recursive Solution<\/strong><\/span><\/h3>\n<pre><strong>int getCount(head)<\/strong>\r\n1) If head is NULL, return 0.\r\n2) Else return 1 + getCount(head-&gt;next)<\/pre>\n<h3 id=\"python-programming-2\"><span style=\"color: #ff0000;\"><strong>Python Programming:<\/strong><\/span><\/h3>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># A complete working Python program to find length of a<br\/># Linked List recursively<br\/> <br\/># Node class<br\/>class Node:<br\/>    # Function to initialise the node object<br\/>    def __init__(self, data):<br\/>        self.data = data  # Assign data<br\/>        self.next = None  # Initialize next as null<br\/> <br\/> <br\/># Linked List class contains a Node object<br\/>class LinkedList:<br\/> <br\/>    # Function to initialize head<br\/>    def __init__(self):<br\/>        self.head = None<br\/> <br\/> <br\/>    # This function is in LinkedList class. It inserts<br\/>    # a new node at the beginning of Linked List.<br\/>    def push(self, new_data):<br\/> <br\/>        # 1 &amp; 2: Allocate the Node &amp;<br\/>        #        Put in the data<br\/>        new_node = Node(new_data)<br\/> <br\/>        # 3. Make next of new Node as head<br\/>        new_node.next = self.head<br\/> <br\/>        # 4. Move the head to point to new Node<br\/>        self.head = new_node<br\/> <br\/>    # This function counts number of nodes in Linked List<br\/>    # recursively, given &#039;node&#039; as starting node.<br\/>    def getCountRec(self, node):<br\/>        if (not node): # Base case<br\/>            return 0<br\/>        else:<br\/>            return 1 + self.getCountRec(node.next)<br\/> <br\/>    # A wrapper over getCountRec()<br\/>    def getCount(self):<br\/>       return self.getCountRec(self.head)<br\/> <br\/># Code execution starts here<br\/>if __name__==&#039;__main__&#039;:<br\/>    llist = LinkedList()<br\/>    llist.push(1)<br\/>    llist.push(3)<br\/>    llist.push(1)<br\/>    llist.push(2)<br\/>    llist.push(1)<br\/>    print &#039;Count of nodes is :&#039;,llist.getCount()<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<h3 id=\"output-2\"><span style=\"color: #339966;\"><strong>Output:<\/strong><\/span><\/h3>\n<pre>count of nodes is 5<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Python Algorithm &#8211; Find Length of a Linked List both Iterative and Recursive &#8211; Linked List &#8211; Write a C function to count number of nodes in a given singly<\/p>\n","protected":false},"author":1,"featured_media":31259,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[79476,4148,79478],"tags":[72483,80240,80236,80239,80231,80237,80241,80232,80238,80235,80234,80230,80233],"class_list":["post-26868","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-linked-list","category-python","category-singly-linked-list","tag-c-linked-list","tag-find-length-of-linked-list-java","tag-geeksforgeeks","tag-get-length-of-linked-list-python","tag-how-to-calculate-the-length-of-linked-list-without-using-counter-in-java","tag-how-to-find-the-length-of-a-linked-list-python","tag-length-of-linked-list-c","tag-length-of-linked-list-python","tag-linked-list-implementation-in-python","tag-linkedlist-java","tag-recursive-linked-list-java","tag-size-of-linked-list-c","tag-what-is-a-class-loader-what-does-it-do"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26868","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26868"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26868\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31259"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26868"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26868"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26868"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}