19. Remove Nth Node From End of List

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        
        ListNode t1=head;
        ListNode t2=head;
        ListNode last=null;
        for(int i=0;i<n;i++)
        {
            t1=t1.next;
        }
        
        while(t1!=null)
        {
            
            t1=t1.next;
            last=t2;
            t2=t2.next;
        }
        
        if(last==null)
        {
            //去头
            return head.next;
        }
        else
        {
            last.next=last.next.next;
        }
        return head;
    }
}

 

posted @ 2016-08-09 23:36  阿怪123  阅读(130)  评论(0编辑  收藏  举报