2014年5月12日星期一

Loop Solution - Remove Nth Node From End of List

The idea is to find the K node, by extend range and move the range. Set newHead made the code easier.

/**
 * 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) {
        if(head == null || head.next == null){
            return null;
        }
        ListNode newHead = new ListNode(Integer.MIN_VALUE);
        ListNode nEndNode = head;
        newHead.next = head;
        for(int i = 1; i < n; i++){
            nEndNode = nEndNode.next;
        }
        ListNode preNode = newHead;
        while(nEndNode.next != null){
            nEndNode = nEndNode.next;
            preNode = head;
            head = head.next;
        }
        preNode.next = head.next;
        return newHead.next;
    }
}

没有评论: