刪除連結串列元素,技巧是設定一個虛擬頭節點,這樣就可以把原始頭節點當做普通節點處理了,最後再返回虛擬頭結點的next即可。
題203. 移除連結串列元素
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null){
return null;
}
ListNode vir = new ListNode();
vir.next = head;
ListNode cur1 = vir;
ListNode cur2 = vir.next;
while(cur2!=null){
if(cur2.val==val){
cur1.next = cur2.next;
cur2 = cur1.next;
}else{
cur1=cur2;
cur2=cur2.next;
}
}
return vir.next;
}
}