Could someone be a kind soul and check my solution?


  • 0
    C
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if(head == null) {
                return head;
            }
            ListNode curr = head;
            int length = 1;
            while(curr.next != null) {
                curr = curr.next;
                length += 1;
            }
            if(n >= length) { return null;}
            int pos = length - n;
            ListNode start = head;
            ListNode prev = null;
            for(int i=0; i<pos; i++) {
                prev = start;
                start = start.next;
            }
            if(prev == null) {
                head = head.next;
            } else {
                prev.next = start.next;
                start.next = null;
            }
            return head;
        }
    }
    

    And the code is currently failed for test case:
    Input [1,2], 2
    output []
    expected [2]


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.