leetcode 19

34 阅读1分钟
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {


        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = head;
        ListNode* slowIndex =  dummyHead;
        ListNode* fastIndex =  dummyHead;
        
        while(n--&&fastIndex->next!=nullptr){
            fastIndex = fastIndex->next;
        }
        while(fastIndex->next!=nullptr){
            fastIndex = fastIndex->next;
            slowIndex = slowIndex->next;
        }
        ListNode* tmp = slowIndex->next;
        slowIndex->next = slowIndex->next->next;
        // delete(tmp);
        return dummyHead->next;
    }
};