题目:
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
使用2个指针,一个指向当前节点curNode,一个指向上一个节点lastNode,若curNode.val == val,则删除当前节点;
代码:
/**
* 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) {
ListNode curNode = head;
ListNode lastNode = null;
while(curNode != null){
if(curNode.val == val){
if(lastNode == null){ // head node
head = curNode.next;
} else {
lastNode.next = curNode.next;
}
} else {
lastNode = curNode;
}
curNode = curNode.next;
}
return head;
}
}