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
- first make sure head points to first element not equal to vlaue
- start checking process to remove the element
- checking the temp.next.val (using temp.next, we need to amke sure temp != null and temp.next!=null)
/**
* 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) {
if(head==null) return null;
while(head!=null && head.val==val){
head= head.next;
}
ListNode temp = head;
//assume first is not same value
while(temp!=null && temp.next!=null){
if(temp.next.val==val){
ListNode node = temp.next.next;
temp.next.next = null;
temp.next = node;
}
else{
temp = temp.next;
}
if(temp==null) break;
}
return head;
}
}