leetcode

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

力扣链接

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        // 求链表长度
    	ListNode* cnt = head;
    	int len = 0;
    	while(cnt){
    		len++;
    		cnt = cnt->next;
    	}

        // 走num步就跳过
    	ListNode* dummyhead = new ListNode(0);
    	dummyhead->next = head;
    	ListNode* current = dummyhead;
        int num = len - n;
    	while(num--){
    		current = current->next;
    	}
    	current->next = current->next->next;
    	return dummyhead->next;
    }
};
// 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) {
        ListNode *dummyhead = new ListNode(0);
        dummyhead->next =head;
        ListNode *slow = dummyhead, *fast = dummyhead;
        while(n-- && fast){
            fast = fast->next;
        }
        while(fast->next){
            slow =slow->next;
            fast = fast->next;
        }
        ListNode*tmp = slow->next;
        slow->next = slow->next->next;
        delete tmp;
        tmp = NULL;
        return dummyhead->next;
    }
};