美文网首页
剑指 Offer 18. 删除链表的节点

剑指 Offer 18. 删除链表的节点

作者: ttiga | 来源:发表于2021-10-19 13:19 被阅读0次
image.png
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteNode(ListNode head, int val) {
        // 假如头结点就是要删除的节点,直接返回下一个下一个节点
        if(head.val == val){
            return head.next;
        }
        // 初始化前驱指针和当前指针
        ListNode pre = head;
        ListNode cur = head.next;
        // 当当前节点结点不为空却不是要输出的值时,遍历链表
        while(cur != null && cur.val != val){
            pre = cur;
            cur = cur.next;
        }
        // 当遍历到要删除的值时
        if(cur != null){
            // 删除指定的节点
            pre.next = cur.next;
        }
        // 返回头结点(整个链表)
        return head;
    }
}

相关文章

网友评论

      本文标题:剑指 Offer 18. 删除链表的节点

      本文链接:https://www.haomeiwen.com/subject/vamooltx.html