移除整数链表中所有与 val 值相同的元素。
举例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
/*
* 203. Remove Linked List Elements
* https://leetcode.com/problems/remove-linked-list-elements/
* https://www.whosneo.com/203-remove-linked-list-elements/
*/
public class RemoveElements {
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode node = head;
for (int i = 2; i < 10; i++) {
node.next = new ListNode(i);
node = node.next;
}
node.next = new ListNode(6);
node = node.next;
node.next = new ListNode(3);
RemoveElements solution = new RemoveElements();
solution.print(head);
head = solution.removeElements(head, 6);
solution.print(head);
head = solution.removeElements(head, 3);
solution.print(head);
}
private void print(ListNode node) {
for (; node != null; node = node.next) {
System.out.print(node.val);
System.out.print("->");
}
System.out.println("null");
}
private ListNode removeElements(ListNode head, int val) {
while (head != null && head.val == val)
head = head.next;
if (head == null)
return null;
ListNode node = head;
while (node.next != null) {
if (node.next.val == val)
node.next = node.next.next;
else
node = node.next;
}
return head;
}
}