203. Remove Linked List Elements

Easy

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

 

package leetcode.easy;

/**
 * Definition for singly-linked list. public class ListNode { int val; ListNode
 * next; ListNode(int x) { val = x; } }
 */
public class RemoveLinkedListElements {
	private static void print(ListNode l) {
		if (l == null) {
			return;
		}
		while (l != null) {
			System.out.print(l.val);
			if (l.next != null) {
				System.out.print("->");
			}
			l = l.next;
		}
		System.out.println();
	}

	public ListNode removeElements(ListNode head, int val) {
		if (head == null) {
			return head;
		}
		if (head.val == val) {
			return removeElements(head.next, val);
		} else {
			ListNode p = head;
			while (p.next != null) {
				if (p.next.val == val) {
					p.next = p.next.next;
				} else {
					p = p.next;
				}
			}
			return head;
		}
	}

	@org.junit.Test
	public void test() {
		ListNode ln1 = new ListNode(1);
		ListNode ln2 = new ListNode(2);
		ListNode ln3 = new ListNode(6);
		ListNode ln4 = new ListNode(3);
		ListNode ln5 = new ListNode(4);
		ListNode ln6 = new ListNode(5);
		ListNode ln7 = new ListNode(6);
		ln1.next = ln2;
		ln2.next = ln3;
		ln3.next = ln4;
		ln4.next = ln5;
		ln5.next = ln6;
		ln6.next = ln7;
		ln7.next = null;
		print(ln1);
		print(removeElements(ln1, 6));
	}
}