Ahri-珊
day13将分享LeetCode算法题203。
203. Remove Linked List Elements
删除链表中值为val的元素。
心路历程
1.链表为空,返回空
2.链表第一位为要删除的元素,返回空
3.删除首部需要删除的元素
4.对剩下的元素进行遍历,找到要删除的元素删除(head = head.next)
代码:
var removeElements = function(head, val) {
if(head == null){
return null;
}
if(head.next == null && head.val == val){
return null;
}
while(head.val == val){
if(head.next == null){
break;
}
head = head.next;
}
console.log(head);
if(head.val == val){
return null;
}
var p = head;
while(head.next != null){
if(head.next.val == val){
head.next = head.next.next;
}
else{
head = head.next;
}
if(head.next == null){
break;
}
}
head = p;
return head;
}
Comments