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

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

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

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param head ListNode类
 * @param n int整型
 * @return ListNode类
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n ) {
    // write code here
    struct ListNode* low, *fast, *pre, *p;
    p = pre = low = fast = head;
    int num = 0;
    while (p) {
        num++;
        p = p->next;

    }
    if (num < 1 || n == 0) {
        return head;
    }
    if (num == n) {
        return head->next;
    }
    p=head;
    if (n==1) {
        for (int i=0; i<num-2; i++) {
            p=p->next;
        
        }
        p->next=NULL;
        return head;
    
    }
    for (int i = 0; i < n; i++) {
        fast = fast->next;

    }
    int j = 0;
    while (fast != NULL) {
        fast = fast->next;
        low = low->next;
        j++;
       
        // if (j % 2 == 0) {
        //     pre = pre->next;

        // }

    }
     for (int i=0; i<j-1; i++) {
            pre=pre->next;
        
        }
    pre->next = low->next;
    return head;
}

全部评论

相关推荐

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