Remove Linked List Elements Java Program - The Coding Shala
Home >> Interview Questions >> Remove Linked list elements
Remove Linked List Elements
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
Remove Linked List Elements Java Program
Approach:
Remove head if match and iterate through the linked list if match skips that node.
Java Code
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode removeElements(ListNode head, int val) { while(head != null && head.val == val) head = head.next; if(head == null) return null; ListNode curr = head; while(curr.next != null){ if(curr.next.val == val){ curr.next = curr.next.next; }else{ curr = curr.next; } } return head; } }
Other Posts You May Like
Comments
Post a Comment