【链表专题】剑指 Offer 18. 删除链表的节点

本问题对应课程链接:剑指offer刷题第三期

要求:
1、请打卡你的解题代码,如果能简单说一下思路则简单说一下思路,请代码不要直接抄袭复制我题解区给的代码哦。
2、给出你代码所用的时间复杂度和空间复杂度

第一次打卡注意:打卡的时候,代码支持 markdown 格式,并且必须要指定语言,比如

共以下 105 个回答

  • 慎言 永久会员 2023年7月16日 下午2:33

    ###C++实现
    /**
    * Definition for singly-linked list.
    * struct ListNode {
    * int val;
    * ListNode next;
    * ListNode(int x) : val(x), next(NULL) {}
    * };
    */
    class Solution {
    public:
    ListNode
    deleteNode(ListNode* head, int val) {
    if(headNULL) return NULL;
    if(head->val
    val) return head->next;
    ListNode* pre=head;
    ListNode* temp=head->next;
    while(temp!=NULL)
    {
    if(temp->valval)
    {
    pre->next=temp->next;
    return head;
    }
    temp=temp->next;
    pre=pre->next;
    }
    return head;
    }
    };

    0 赞同 0 条回复
  • ZJS 永久会员 2023年7月9日 上午10:46

    方法:双指针
    时间复杂度O(n)
    空间复杂度O(1)

    class Solution {
        public ListNode deleteNode(ListNode head, int val) {
            while(head != null && head.val == val){
                head = head.next;
            }
    
            if(head == null || head.next == null)
                return head;
    
            ListNode tmp = head;
            ListNode curr = head.next;
    
            while(curr != null){
                if(curr.val == val){
                    tmp.next = curr.next;
                }else
                    tmp = curr;
    
                curr = curr.next;
            }
    
            return head;
        }
    }
    

    我这个是删除所有值为val的节点

    0 赞同 0 条回复
  • 冬 普通 2023年7月9日 上午9:53

    打卡:
    class Solution {
    public ListNode deleteNode(ListNode head, int val) {
    if(headnull){
    return null;
    }
    if(head.val
    val){
    return head.next;
    }
    ListNode helper=head;
    while(helper.next!=null){
    if(helper.next.valval){
    helper.next=helper.next.next;
    break;
    }else{
    helper=helper.next;
    }
    }
    return head;
    }
    }

    0 赞同 0 条回复
  • CaCO3 永久会员 2023年7月7日 下午9:08

    ”’java
    class Solution {
    public ListNode deleteNode(ListNode head, int val) {
    if(head null){
    return null;
    }
    if(head.val
    val){
    return head.next;
    }
    //给一个虚拟头结点
    ListNode pre = new ListNode(0);
    pre.next = head;
    ListNode now = head;
    while(now != null){
    if(now.val val){
    pre.next = now.next;
    break;
    }else{
    pre = now;
    now = now.next;
    }
    }
    return head;
    }
    }

    0 赞同 0 条回复
  • 一琬人间烟火 普通 2023年7月7日 下午8:53

    c++ 虚拟头节点
    class Solution {
    public:
    ListNode* deleteNode(ListNode* head, int val) {
    ListNode* dummyHead = new ListNode(1);
    dummyHead->next = head;
    ListNode* cur = dummyHead;
    while (cur->next != NULL) {
    if(cur->next->val val) {
    cur->next = cur->next->next;
    break;
    } else {
    cur = cur->next;
    }
    }
    head = dummyHead->next;
    delete dummyHead;
    return head;
    }
    };

    0 赞同 0 条回复

# 回答此问题

后才能回答