-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLengthOfLL.java
More file actions
85 lines (66 loc) · 1.72 KB
/
LengthOfLL.java
File metadata and controls
85 lines (66 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Length Of LL
// Send Feedback
// Given the head of a singly linked list of integers, find and return its length.
// Example:
// Sample Linked List
// The length of the list is 4. Hence we return 4.
// Note:
// Exercise caution when dealing with edge cases, such as when the head is NULL. Failing to handle these edge cases appropriately may result in a runtime error in your code.
// Input format :
// The first and only line contains elements of the singly linked list separated by a single space, -1 indicates the end of the singly linked list and hence, would never be a list element.
// Output format :
// Return a single integer denoting the length of the linked list.
// Sample Input 1 :
// 3 4 5 2 6 1 9 -1
// Sample Output 1 :
// 7
// Explanation of sample input 1 :
// The number of nodes in the given linked list is 7.
// Hence we return 7.
// Sample Input 2 :
// 10 76 39 -3 2 9 -23 9 -1
// Sample Output 2 :
// 8
// Expected Time Complexity:
// Try to do this in O(n).
// Constraints :
// 0 <= N <= 10^5
// Time Limit: 1 sec
class Node{
public int data;
public Node next;
Node()
{
this.data = 0;
this.next = null;
}
Node(int data)
{
this.data = data;
this.next =null;
}
Node(int data, Node next)
{
this.data = data;
this.next = next;
}
}
public class LengthOfLL {
public static void main(String[] args) {
}
public static int length(Node head){
//Your code goes here
if(head==null)
{
return 0;
}
Node temp = head;
int length = 0;
while(temp!=null)
{
temp = temp.next;
length++;
}
return length;
}
}