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

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

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

/**
 * struct ListNode {
 *    int val;
 *    struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param n int整型 
     * @return ListNode类
     */
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        // write code here
        ListNode* slow = head;
        ListNode* fast = head->next;
        if(fast==NULL){
            return NULL;
        }

        int i = 0;
        while(i<n-1){
            fast = fast->next;
            if(fast==NULL){
                return head->next;
            }
            i++;
        }


        while(fast->next!=NULL){
            slow = slow->next;
            fast = fast->next;
        }
        slow->next = slow->next->next;
        return head;
    }
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务