From af161caf87dc526041431c67ea895456d17c44e5 Mon Sep 17 00:00:00 2001 From: Elvis Otieno <125451537+the1Riddle@users.noreply.github.com> Date: Sun, 3 Mar 2024 11:02:51 +0300 Subject: [PATCH] remove-nth-node-from-end-of-list --- C#/remove-nth-node-from-end-of-list.cs | 60 ++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 C#/remove-nth-node-from-end-of-list.cs diff --git a/C#/remove-nth-node-from-end-of-list.cs b/C#/remove-nth-node-from-end-of-list.cs new file mode 100644 index 0000000..2b3a269 --- /dev/null +++ b/C#/remove-nth-node-from-end-of-list.cs @@ -0,0 +1,60 @@ +/** + * 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 +{ + // Returns a ListNode + public ListNode RemoveNthFromEnd(ListNode head, int n) + { + ListNode dummy = new ListNode(-1); + dummy.next = head; + ListNode slow = dummy, fast = dummy; + + for (int i = 0; i < n; i++) + { + fast = fast.next; + } + + while (fast.next != null) + { + slow = slow.next; + fast = fast.next; + } + + slow.next = slow.next.next; + + return dummy.next; + } +} + +/** SOLUTION TWO **/ + +public class Solution { + public ListNode RemoveNthFromEnd(ListNode head, int n) { + ListNode current = head; + Dictionary nodePositions = new(); + + int i = 0; + while (current != null) { + nodePositions[i] = current; + current = current.next; + i++; + } + + if (i - n == 0) { + return head.next; + } + + nodePositions[i - n - 1].next = nodePositions[i - n].next; + + return head; + } +}