题解 | #删除链表的倒数第n个节点#

删除链表的倒数第n个节点

http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6

双指针,没什么好说的

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        // write code here
        if(!head) return head;
        ListNode* fast = head;
        ListNode* slow = head;
        for(int i = 0; i < n && head; ++i) { fast = fast->next; }
        if(!fast) return head->next;
        while(fast->next) {
            fast = fast->next;
            slow = slow->next;
        }
        slow->next = slow->next->next;
        return head;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务