删除链表节点
删除链表的节点
https://www.nowcoder.com/practice/f9f78ca89ad643c99701a7142bd59f5d?tpId=13&tqId=2273171&ru=/exam/oj/ta&qru=/ta/coding-interviews/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D13%26type%3D13
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param val int整型
* @return ListNode类
*/
public ListNode deleteNode (ListNode head, int val) {
// write code here
ListNode pre = new ListNode(-1);
pre.next = head;
ListNode cur = pre; // 为什么cur的变化会引起pre的改变?
// ——Java语法,这里是变量赋值,实际上是cur变量指向pre所指向的那个地址,即对该地址的引用;那么,当该地址上面的值发生变化(cur导致),那么pre也将发生变化!!!
// 但是为什么:cur=cur.next时不发生变化?仅仅在cur.next = cur.next.next;时pre才发生变化?
// 其实,cur内的元素指向,会影响pre的元素指向
while(cur != null) {
if(cur.next.val == val) {
cur.next = cur.next.next;
break;
}
cur = cur.next;
}
return pre.next;
}
}
疑问:为什么cur = cur.next;不会让pre发生变化?
而cur.next = cur.next.next;会让pre发生变化?(现象可以由牛客刷题界面的调试功能观察到)
解释:cur=cur.next并没有改变pre内元素的指向,而cur.next=cur.next.next会改变pre内元素的指向。