if(head==NULL)
return head;
Node*temp=head;
head=head->next;
delete temp;
return head;
}
Problem of the day
You are given a singly linked list of length ’n’ . Your task is to delete the head of a linked list.
Input: 5 -> 8 -> 3 -> 7 -> 9
Output: 8 -> 3 -> 7 -> 9
Explanation: The head of the given list is at 5. After deletion of head, new list is 8 -> 3 -> 7 -> 9.
The first line contains an integer ‘n’, the number of elements present in the linked list.
The next line contains ‘n’ space-separated integers denoting the elements of the linked list.
Output Format:-
The output contains the elements of linked list. If the modified list is empty, then -1 is printed.
Note:-
You don’t need to print anything. Just implement the given function.
4
3 1 8 7
1 8 7
Given list: 3 -> 1 -> 8 -> 7
Head of the given list is at 3.
After deletion, updated list is 1 -> 8 ->7
3
1 3 5
3 5
1 <= ‘n’ <= 10^5
1 <= 'data' <= 10^9
where 'data' is the values of node in a linked list.
Time Limit: 1 sec
Approach:
This approach removes the first node (head) from a singly linked list. It first checks if the list is empty or contains only one element; if so, it returns NULL. If the list has more than one element, it creates a temporary pointer to the head node, updates the head pointer to the next node, and then deletes the old head node. This effectively removes the head node and returns the updated head pointer.
Algorithm:
Function deleteHead(head):
O(1)
The time complexity is O(1), as it uses a constant amount of time regardless of the size of the singly linked list.
O(1)
The space complexity is O(1), as it uses a constant amount of extra space regardless of the size of the singly linked list.
Interview problems
c++ solution
if(head==NULL)
return head;
Node*temp=head;
head=head->next;
delete temp;
return head;
}
Interview problems
JAVA || 1 line solution ||
public class Solution {
public static Node deleteHead(Node head) {
// Write Code Here.
return head.next;
}
}
Interview problems
Easy c++ solution
Node * deleteHead(Node *head) {
// Write your code here.
if(head == NULL){
return nullptr;
}
head = head -> next;
return head;
}
Interview problems
Python One Liner :)
return None if head is None or head.next is None else head.next
Garbage collection GC will take care of deleting
Interview problems
Easy Python Solution
def deleteHead(head: Optional[Node]) -> Optional[Node]:
# Write your code here
if (head is None):
return None
else:
head=head.next
return head
pass
Interview problems
Java Solution
public static Node deleteHead(Node head) {
if (head == null)
return null;
head = head.next;
return head;
}
Interview problems
Java Solution
public class Solution {
public static Node deleteHead(Node head) {
// Write Your Code Here.
if(head==null || head.next==null){
return null;
}
else{
head=head.next;
}
return head;
}
}