LintCode 删除链表中倒数第n个节点

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */


public class Solution {
    /*
     * @param head: The first node of linked list.
     * @param n: An integer
     * @return: The head of linked list.
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // write your code here
        if(head.next==null && n==1)
        {
            return null;
        }
        ListNode preNode=head;
        ListNode currentNode=head;
        ListNode goalNode=head;
        for(int i=1;i<=n;i++)
        {
            currentNode=currentNode.next;
        }
        if(currentNode==null)
        {
            ListNode resultNode=head.next;
            head=null;
            return resultNode;
        }
        while(currentNode!=null)
        {
            currentNode=currentNode.next;
            preNode=goalNode;
            goalNode=goalNode.next;
        }
        preNode.next=goalNode.next;
        goalNode=null;
        return head;
    }
}

 

posted @ 2017-10-10 15:31  temporary  阅读(129)  评论(0编辑  收藏  举报