[leedcode 19]Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.


/**
 * 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) {
        //题眼:两个指针,一快一慢,步长为n
        //注意几点:
        //1.判断输入的整数范围
        //2.删除的是头结点的处理方式(画图)
        
        if(n<=0)return null;
        ListNode right=head;
        while(n>0){
            right=right.next;
            n--;
        }
        ListNode left=head;
        if(right==null)return head.next;//注意删除第一个节点的例外
        while(right.next!=null){
            left=left.next;
            right=right.next;
        }
        left.next=left.next.next;//删除节点
         return head;
        
    }
}

 

posted @ 2015-07-07 15:39  ~每天进步一点点~  阅读(81)  评论(0编辑  收藏  举报