[LeetCode]19. Remove Nth Node From End of List

链表的删除

Posted by JinFei on December 28, 2019

题目描述

Given a linked list, remove the n-th node from the end of list and return its head.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

Example:

Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.

解题思路

  • 比如首先要考虑的时,如何找到倒数第N个节点,由于只允许一次遍历,所以不能用一次完整的遍历来统计链表中元素的个数,而是遍历到对应位置就应该移除了。
  • 那么就需要用两个指针来帮助解题,pre 和 cur 指针。
  • 首先 cur 指针先向前走N步,如果此时 cur 指向空,说明N为链表的长度,则需要移除的为首元素,那么此时返回 head->next 即可,如果 cur 存在,再继续往下走,此时 pre 指针也跟着走,直到 cur 为最后一个元素时停止,此时 pre 指向要移除元素的前一个元素,再修改指针跳过需要移除的元素即可

C++代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(head == nullptr){
            return head;
        }
        ListNode* fast = head;
        ListNode* slow = head;
        while(n > 0){
            fast = fast -> next;
            n--;
        }
        // 重点 检查 这里是否为空
        if(fast == nullptr){
            return head -> next;
        }
        while(fast -> next){
            fast = fast -> next;
            slow = slow -> next;
        }
        slow -> next = slow -> next -> next;
        return head;
        
    }
};
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(head == NULL){
            return NULL;
        }
        ListNode* pre = head, *cur = head;
        for(int i = 0; i < n; i++){
            cur = cur -> next;
        }
        if(cur == NULL){
            return head -> next;
        }
        while(pre && cur -> next){
            pre = pre -> next;
            cur = cur -> next;
        }
        pre -> next = pre -> next -> next;
        return head;
    }
};