问题描述
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。返回删除后的链表的头节点。
代码
public class Main {
public static void main(String[] args) {
ListNode head = new ListNode(4);
ListNode n2 = new ListNode(5);
ListNode n3 = new ListNode(1);
ListNode n4 = new ListNode(9);
head.next = n2;
n2.next = n3;
n3.next = n4;
ListNode res = deleteNode(head, 5);
while (res != null) {
System.out.println(res.val);
res = res.next;
}
}
public static ListNode deleteNode(ListNode head, int val) {
ListNode temp = head;
if (temp.val == val) return head.next;
while(temp.next != null) {
if (temp.next.val == val) {
temp.next = temp.next.next;
}
temp = temp.next;
}
return head;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}