1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/cs/delete-the-middle-node-of-a-linked-list.cs
2024-01-07 23:14:58 +01:00

43 lines
863 B
C#

/**
* 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;
}
}