llllmz

导航

19. 删除链表的倒数第 N 个结点C

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    if(!head) return NULL;
    int i=0;
    struct ListNode* tem=head;
    struct ListNode* pre=NULL;
    int j=0;
    while(tem){
        j++;
        tem=tem->next;
    }
    tem=head;
    if(n>j) return head;
    if(n==j){
        head=head->next;
        free(tem);
        return head;
    }
    while(i!=j-n && tem){
        i++;
        pre=tem;
        tem=tem->next;
    }
    if(!tem) return head;
    pre->next=tem->next;
    free(tem);
    return head;
}

结果:

 

posted on 2024-02-28 16:30  神奇的萝卜丝  阅读(14)  评论(0)    收藏  举报