1. 程式人生 > >[leetcode]19. Remove Nth Node From End of Liste

[leetcode]19. Remove Nth Node From End of Liste

/**
 * 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 p=head;
        int sum=0;
        
        while(p!=null){
            sum++;
            p=p.next;
        }
        
        int m=sum-n;
        
        if(m==0){
            head=head.next;
            return head;
        }
        
        p=head;
        
        for(int i=0;i<m-1;i++){
            p=p.next;
        }
        
        p.next=p.next.next;
        
        return head;
    }
}

Solution 2:追擊辦法 one pass

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 fast=head;
        ListNode curr=head;
        
        for(int i=1;i<=n;i++){
            fast=fast.next;
        }
        
        if(fast==null){
            head=head.next;
            return head;
            
        }
        
        while(fast.next!=null){
            fast=fast.next;
            curr=curr.next;
        }
        
        curr.next=curr.next.next;
        
        return head;
    }
}