删除链表元素,技巧是设置一个虚拟头节点,这样就可以把原始头节点当做普通节点处理了,最后再返回虚拟头结点的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;
}
}
标签:vir,ListNode,val,训练营,随想录,next,链表,cur2
From: https://www.cnblogs.com/hailicy/p/18286759