LeetCode每日一题 (43) 19. 删除链表的倒数第N个节点

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


在这里插入图片描述


class Solution {
    
    
public:
    // 1. 可以先计算出链表的总长度s,然后删除第s-n就可以了
    ListNode* removeNthFromEnd(ListNode* head, int n) {
    
    
        int s=0;
        ListNode *p=head,*pre;
        while(p!=nullptr){
    
    
            s++;
            p=p->next;
        }
        pre=p=head;
        n=s-n;
        if(n==0){
    
     // 说明删除的是第0个
            return head->next;
        }
        while(n--){
    
    
            pre=p;
            p=p->next;
        }
        // 删除p
        pre->next=p->next;
        return head;
    }
};

在这里插入图片描述


双指针:

class Solution {
    
    
public:
    // 使用双指针,初始化first和second距离相差n,那么当second到达尾部的时候,first+1就是需要删除的元素,first=first->next,就完成删除操作
    ListNode* removeNthFromEnd(ListNode* head, int n) {
    
    
        ListNode* first=head;
        ListNode* second=head;
        while(n--){
    
    
            first=first->next;
        }
        if(first==nullptr) return head->next;
        while(first->next!=nullptr){
    
    
            first=first->next;
            second=second->next;
        }
        // 删除
        second->next=second->next->next;
        return head;
    }
};

在这里插入图片描述


猜你喜欢

转载自blog.csdn.net/qq_45021180/article/details/109148985