leetcode 日经贴,Cpp code -Remove Nth Node From End of List

来源:互联网 发布:360免费wifi网络不稳定 编辑:程序博客网 时间:2024/06/05 16:00

Remove Nth Node From End of List

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


0 0