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
题意:去除链表中的目标元素。链表中的值可能有重复
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
//如果链表为空,则返回null
if (head == null) {
return null;
}
//用来保存剩余的链表
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode preNode = dummy;
ListNode curNode = head;
while (curNode.next != null) {
//如果和目标值不等,则两个指针同时向后移动一位
if (curNode.val != val) {
preNode = preNode.next;
curNode = curNode.next;
}else {
//如果和目标值相等,则把preNode指向curNode的下一个节点
//同时,curNode向后移动一位
preNode.next = curNode.next;
curNode = curNode.next;
}
}
//上面的情况当链表尾部为目标值时,判断不到
//所以最后要对链表尾部单独判断
if (curNode.val == val) {
preNode.next = null;
}
return dummy.next;
}
}