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

思路

这道题如果是暴力,其实可以先反转,在删除,在反转,麻烦

Method

  • 双指针:
    思路: 建立一个头节点node,然后fast和slow指针都指向node,然后fast先跑n + 1距离,
    fast先走,就会与slow就会相隔多少距离,到最后fast走到nullptr,slow就是指向当前节点的previos节点
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* node = new ListNode(0);
        node->next = head;
        ListNode* fast = node;
        ListNode* slow = node;
        //快指针先走n+1;这样与慢指针就相差n+1个距离
        int index = n + 1;
        while (index-- && fast != nullptr) {
            fast = fast->next;
        }
        //然后快慢指针一起走
        while (fast != nullptr) {
            fast = fast->next;
            slow = slow->next;
        }
        //因为slow与fast相差n+1个单位就说明slow指向被删节点的前一个节点
        slow->next = slow->next->next;
        return node->next;
    }
};
  • 递归

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int pos = length(head,n);
        //头节点不一样,没有前面的节点
        if(pos == n){
            head = head.next;
        }
        return head;
    }
    public int length(ListNode head,int n){
        if(head == null){
            return 0;
        }
        int post = length(head.next,n)+1;
        //删除这个节点要得到其前面的节点
        if(post == n + 1){
            head.next = head.next.next;
        }
        return post;
    }
}

posted @ 2023-02-25 09:53  壹剑霜寒十四州  阅读(10)  评论(0编辑  收藏  举报