19. Remove Nth Node From End of List

18-09-23 11:41PM
mail@pastecode.io avatarunknown
plain_text
4 days ago
1.3 kB
3
Indexable
Never
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public static int lenLL(ListNode head){
        ListNode curr = head;
        int length = 0;
        while(curr != null){
            length++;
            curr = curr.next;
        }
        return length;
    }
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int lenOfLL = lenLL(head);
        int actualPos = lenOfLL - n;
        ListNode curr = head;
        ListNode curr2 = head;
        int pos = 0;
        if(head.next == null){
            return null;
        }
        else if(actualPos == 0){
            return head.next;
        }
        else{
        while(curr != null){
            if(pos == (actualPos - 1)){
                curr2 = curr2.next.next;
                curr.next = curr2;
                break;
            }
            else{
            pos++;
            curr = curr.next;
            curr2 = curr2.next;
            continue;
            }
        }
        return head;
        }
    }
}