Java accepted solution.


  • 0
    O
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode removeElements(ListNode head, int val) {
        	while (head != null && head.val == val) {
        		head = head.next;
        	}
        	if (head == null) {
        		return null;
        	}
        	ListNode second = head.next, first = head;
        	while(second != null && second.next != null) {
        		if (second.val == val) {
        			second.val = second.next.val;
        			second.next = second.next.next;
        		} else {
        			second = second.next;
        			first  = first.next;
        		}
        	}
        	if (second != null && second.val == val) {
        		first.next = null;
        	}
        	return head;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.