题目:
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
例子:
题解1:(双指针)
public ListNode deleteNode(ListNode head, int val) {
ListNode pre = null;
ListNode post = head;
while (head.getVal()!=val){
// 指针后移,知道post等于目标值
pre = post;
post = post.next;
}
// 此时退出的post指针指向当前的值,post.next = null,释放强引用,垃圾回收
pre.next = post.next;
post.next = null;
return head;
}