cs: add “2095. Delete the Middle Node of a Linked List”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
2dff3c1d16
commit
20632b1d7c
1 changed files with 43 additions and 0 deletions
43
cs/delete-the-middle-node-of-a-linked-list.cs
Normal file
43
cs/delete-the-middle-node-of-a-linked-list.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue