Write a program to find the length of the linked list.
Example 1:
Input: 5->2->8->4->1->NULL
Output: 5
Approach
Java
public class LinkedListLength {public static void main(String[] args) {ListNode l = new ListNode(1);l.next = new ListNode(2);l.next.next = new ListNode(3);l.next.next.next = new ListNode(4);l.next.next.next.next = new ListNode(5);int length = linkedListLength(l);System.out.println("Length of link list is " + length);}private static int linkedListLength(ListNode node) {int length = 0;while (node != null) {node = node.next;length++;}return length;}}class ListNode {int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}}//Time Complexity: O(n)//Space Complexity: O(1)
C++
#include <bits/stdc++.h>using namespace std;//Struture of nodestruct Node{int data;Node *next;Node(int data){this->data=data;this->next=NULL;}};//function to find the length//of a linked listint linkedListLength(Node *head){Node *temp=head;int length=0;//iterate till we reach end of the linked//listwhile(temp!=NULL){//increment the lengthlength++;//move to next nodetemp=temp->next;}//return the lengthreturn length;}int main(){Node *head=new Node(5);head->next=new Node(2);head->next->next=new Node(8);head->next->next->next=new Node(4);head->next->next->next->next=new Node(1);cout<<"Length of Linked list is ";cout<<linkedListLength(head);return 0;}//Time Complexity: O(n)//Space Complexity: O(1)
No comments:
Post a Comment