Skip to content

Latest commit

 

History

History
94 lines (70 loc) · 1.95 KB

_2095. Delete the Middle Node of a Linked List.md

File metadata and controls

94 lines (70 loc) · 1.95 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 06, 2024

Last updated : July 01, 2024


Related Topics : Linked List, Two Pointers

Acceptance Rate : 59.038 %


Solutions

C

// Took ~1.5 minutes --> did it right after the java vers

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* deleteMiddle(struct ListNode* head) {
    if (!head || !head->next) {
        return NULL;
    }

    struct ListNode* slow = head;
    struct ListNode* fast = head->next;

    while (fast->next && fast->next->next) {
        slow = slow->next;
        fast = fast->next->next;
    }

    slow->next = slow->next->next;
    
    return head;
    
}

Java

// 2.67 minutes to complete :D

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteMiddle(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }

        ListNode slow = head;
        ListNode fast = head.next;

        while (fast != null && fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        slow.next = slow.next.next;

        return head;
    }
}