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

难度:中等。
双指针,重点是思路,实现简单。

正确解法:

/**
 * 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 == NULL)return head;
        if(head->next == NULL && n == 1)return NULL;
        ListNode * result = head, *temp = head;
        for(int i = 0; i < n; i++){
    
    
            temp = temp -> next;
        }
        if(temp == NULL){
    
    
            return head->next;
        }
        while(temp->next != NULL){
    
    
            result = result->next;
            temp = temp->next;
        }
        result->next = result->next->next;
        return head;
    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/almost_afei/article/details/113146218