Remove Linked List Elements - Linked List - Easy - LeetCode
💻 coding

Remove Linked List Elements - Linked List - Easy - LeetCode

1 min read 126 words
1 min read
ShareWhatsAppPost on X
  • 1The algorithm removes all nodes with a specified value from a linked list of integers.
  • 2It handles edge cases, such as an empty list or a single node with the target value.
  • 3The solution has a time complexity of O(n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The algorithm removes all nodes with a specified value from a linked list of integers."

Remove Linked List Elements - Linked List - Easy - LeetCode

Remove all elements from a linked list of integers that have value val.

Example:

Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * public int val;
 * public ListNode next;
 * public ListNode(int val=0, ListNode next=null) {
 * this.val = val;
 * this.next = next;
 * }
 * }
 */
public class Solution {
 public ListNode RemoveElements(ListNode head, int val) {
 ListNode temp = head; 
 if(head == null){
 return head;
 }
 
 if(head.next == null){
 if(head.val==val){
 return null;
 }
 return head;
 }
 
 while(temp.next!=null){
 if(temp.next.val==val){
 temp.next = temp.next.next;
 }
 else{
 temp = temp.next;
 }
 }
 
 //check if first node is having given value
 if(head.val==val){
 head = head.next;
 }
 
 return head;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 30 September 2020 · 1 min read · 126 words

Part of AskGif Blog · coding

You might also like

Remove Linked List Elements - Linked List - Easy - LeetCode | AskGif Blog