Remove Linked List Elements

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

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

 

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        /*
         * Adding a header will save the case discussion 
         * where head.val == val. 
         */
        ListNode header = new ListNode(0); 
        header.next = head; 
        
        ListNode cur = header;
        //decide if we want to delete the next node 
        while (cur.next != null) {
            if (cur.next.val == val) {
                cur.next = cur.next.next; 
            } else {
                cur = cur.next; 
            }
        }
        return header.next; 
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s