0
点赞
收藏
分享

微信扫一扫

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

zhoulujun 2022-04-17 阅读 52
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
 struct ListNode* Head = malloc(sizeof(struct ListNode));
    Head->next = head;
    struct ListNode* p = Head;
    struct ListNode* q = Head;

    int count=0;
    while(p->next!=NULL){
        if(count<n) count++;
        else q=q->next;
        p=p->next;
    }
    if(count==n){
        q->next=q->next->next;
    }
    return Head->next;
}

//p,q都指向链表的第一个结点,让二者距离为n,当p指向最后一个结点,q就指向倒数第n-1个。
//最后返回头指针

LeetCode题目链接,剑之offer || 021

举报

相关推荐

0 条评论