给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
注意:此题对比原题有改动
示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
说明:
题目保证链表中节点的值互不相同
若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
初始代码:
public ListNode deleteNode(ListNode head, int val) {
ListNode curnext = head.next,cur = head,pre = head;
while(cur != null){
if(cur.val == val){
if(cur == head){
return curnext;
}else{
pre.next = cur.next;
return head;
}
}
pre = cur;
cur = curnext;
curnext = cur.next;
}
return head;
}
优化之后:
class Solution {
public ListNode deleteNode(ListNode head, int val) {
//只需要先判断特殊情况
if(head.val == val) return head.next;
ListNode pre = head, cur = head.next;
// 循环终止条件,当当前节点不为null,且值不等于要删除的节点
// 那么跳出循环肯定就是这两个条件之一了
while(cur != null && cur.val != val) {
pre = cur;
cur = cur.next;
}
// 判断跳出循环是因为哪个条件,不是第一个条件,那自然是第二个条件、
// 如果是第二个条件,则删除对应节点
if(cur != null) pre.next = cur.next;
return head;
}
}
题目解析代码中写的挺清楚的了。
读书时不必把所有的知识点都记下来,要记的就是那些你留下的笔记与线索,要记的是那些核心的知识点。
其他的到用到的时候按图索骥就可以了。