您的位置:首页 > Web前端 > Node.js

[Leetcode 19, Easy] Remove Nth Node From End of List

2015-02-23 10:41 489 查看
Problem:

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.


Note:

Given n will always be valid.

Try to do this in one pass.
Analysis:

The key idea to this problem that the two pointers that we assigned for this linked list should have distance n nodes. Then the back pointer will point to the node we need to remove when the front point point to the last node of this linked list.

Solution:

C++:

ListNode *removeNthFromEnd(ListNode *head, int n) {
        if(n == 0)
            return head;
            
        ListNode* pBack = head;
        ListNode* pFront = head;
        for(int i = 0; i < n; ++i) {
            pFront = pFront->next;
        }
        
        if(pFront == NULL) {
            head = pBack->next;
            delete pBack;
            return head;
        }
        
        while(pFront->next != NULL) {
            pFront = pFront->next;
            pBack = pBack->next;
        }
        
        ListNode* pDelete = pBack->next;
        pBack->next = pBack->next->next;
        delete pDelete;
        
        return head;
        
    }


Java:

Python:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: