美文网首页
19. Remove Nth Node From End of

19. Remove Nth Node From End of

作者: 蜜糖_7474 | 来源:发表于2019-05-09 20:40 被阅读0次

    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? 你能一遍过吗(笑

    AC代码

    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            if (head->next == NULL) return NULL;
            ListNode *head_cp = head, *shadow = head, *pre_shadow = head;
            n--;
            while (n--) head_cp = head_cp->next;
            while (head_cp->next != NULL) {
                head_cp = head_cp->next;
                pre_shadow = shadow;
                shadow = shadow->next;
            }
            if (pre_shadow != shadow) {
                pre_shadow->next = shadow->next;
                delete shadow;
            }
            else {
                ListNode* t = shadow->next;
                delete shadow;
                return t;
            }
            return head;
        }
    };
    

    总结

    相关文章

      网友评论

          本文标题:19. Remove Nth Node From End of

          本文链接:https://www.haomeiwen.com/subject/xengoqtx.html