19. Remove Nth Node From End of List (JAVA)

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

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.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

 
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode pSlow = head;
        ListNode pFast = head;
        for(int i = 0; i < n; i++){
            pFast = pFast.next;
        }
        
        if(pFast == null){ //remove first node
            return head.next;
        }
        
        while(pFast.next!=null){
            pFast = pFast.next;
            pSlow = pSlow.next;
        }
        pSlow.next = pSlow.next.next;
        return head;
        
    }
}

解题思路:使用快慢指针,实现O(n)遍历。

 

posted on 2019-04-26 16:36  joannae  阅读(96)  评论(0编辑  收藏  举报

导航