Tuesday, June 3, 2014

LeetCode Remove Nth Node From the End of List

Boundary Conditions:
1. Only one node in the list
2. Remove the first node

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode front = head;
        ListNode behind = head;
        //Only one node in the list
        if (head.next == null) return null;
        //Move the front Node n steps
        while (n > 0) {
            front = front.next;
            n--;
        }
        //Remove the first node
        if (front==null) {
            head = head.next;
            return head;
        }
        //Move front and behind at the same time
        while (front.next != null) {
            front = front.next;
            behind = behind.next;
        }
       
        behind.next = behind.next.next;
        return head;
    }

No comments:

Post a Comment