
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
先定义ListNode复制head。然后对head进行遍历,如果val等于题目中的val,直接跳过。
代码:
class Solution {
public ListNode deleteNode(ListNode head, int val) {
ListNode node;
if(head != null){
node = head;
}else{
return null;
}
if(head.val == val){
return head.next;
}
while(head.next != null){
if(head.next.val == val){
head.next = head.next.next;
}else{
head = head.next;
}
}
return node;
}
}
结果: