Skip to content

Latest commit

 

History

History
46 lines (41 loc) · 1.18 KB

203. Remove Linked List Elements.md

File metadata and controls

46 lines (41 loc) · 1.18 KB

203. 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

Solution 1:

  • 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;
    }
}