題目: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
思路:新建一個val=-1的頭節點,從head結點開始,判斷值是否與目標值相等,不相等就加在新建結點後
代碼:
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode cur = new ListNode(-1);
ListNode res = cur ;
while(head!=null){
if(head.val!=val){
cur.next = head;
cur = cur.next;
}
head = head.next;
}
cur.next = null;
return res.next ;
}
}