--

leetcode 019: Remove Nth Node From End of List



https://leetcode.com/problems/remove-nth-node-from-end-of-list/



problem:
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?



start code (c++)
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        
    }
};



solution:

我的思路:
利用两个 node 间隔 n 个距离遍历。


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* head1 = head;
        ListNode* head2 = head;
        for (int i = 0; i < n; i ++){
            head2 = head2->next;
        }
        if (head2 == NULL)
            return head->next;
        
        // remove the first node        
        while (head2->next){
            head2 = head2->next;
            head1 = head1->next;
        }
        
        head1->next =head1->next->next;
        return head;
    }
};