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.
题目解析:该题很容易,需要注意的是找起点的时候要注意没有起点的情况
public ListNode removeElements(ListNode head, int val) {
ListNode from;
ListNode to;
ListNode temp = head;
if (head != null) {
while (temp.val == val) {
if (temp.next == null) {
return null;
} else
temp = temp.next;
}
to = temp;
from = temp;
while (to != null) {
if (to.val != val) {
from = to;
to = to.next;
} else {
to = to.next;
from.next = to;
}
}
return temp;
}
return null;
}