cs: add “2095. Delete the Middle Node of a Linked List”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-01-07 23:14:58 +01:00
parent 2dff3c1d16
commit 20632b1d7c
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,43 @@
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
private int Count(ListNode node) {
var count = 0;
for (; node != null; node = node.next) {
++count;
}
return count;
}
public ListNode DeleteMiddle(ListNode head) {
if (head == null) {
return null;
}
var count = Count(head);
if (count == 1) {
return null;
}
var mid = count >> 1;
var node = head;
for (var i = 0; i < mid - 1; ++i) {
node = node.next;
}
node.next = node.next.next;
return head;
}
}