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
Credits: Special thanks to @mithmatt for adding this problem and creating all test cases.
深夜来了一发,Accept了。
public ListNode removeElements(ListNode head, int val) { if (head == null) return null; while (head.val == val && head.next != null) head = head.next; if (head.val == val && head.next == null) return null; if (head.next != null) { ListNode temp = head, p = head.next; while (p != null) { if (p.val == val) temp.next = p.next; else temp = temp.next; p = temp.next; } } return head; }学习一下别人的算法。
public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; while (head.next != null) { if (head.next.val == val) { head.next = head.next.next; } else { head = head.next; } } return dummy.next; }