Java one pass use List


  • 0
    S
    public class Solution {
        List<ListNode> list;
    	public ListNode removeNthFromEnd(ListNode head, int n) {
    	    if (head.next==null) return null;
    		list = new ArrayList<ListNode>();
    		int length = go(head);
    		if (n==1) list.get(length-2).next = null;
    		else if(length == n) head = head.next;
    		else list.get(length-n-1).next = list.get(length-n+1);
    		return head;
    	}
    	
    	private int go(ListNode node) {
    		if (node == null) return 0;
    		list.add(node);
    		return 1+go(node.next);
    	}
    }
    

Log in to reply
 

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