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
题目链接:https://leetcode.com/problems/remove-linked-list-elements/
题目分析:模拟,注意细节
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
ListNode ans = head;
while (ans != null && ans.val == val) {
ans = ans.next;
}
if (ans == null) {
return ans;
}
head = ans;
while (ans != null) {
while (ans != null && ans.next != null && ans.next.val == val) {
ans.next = ans.next.next;
}
ans = ans.next;
}
return head;
}
}