思路1:
遍历一次找到链表长度N,第二次遍历找到第N-K个节点删除
需要遍历两次
思路2:
首先定义指针P1,指向head,让head走K个节点。
再定义P2让此时的P2指向head。
P1,P2同时移动,当P1到链表尾时,P2指向的就是倒数第K个节点。
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode* dummy = malloc(sizeof(struct ListNode));
dummy->val = 0, dummy->next = head;
struct ListNode* first = head;//P1
struct ListNode* second = dummy;//P2
for (int i = 0; i < n; ++i) {
first = first->next;
}
while (first) {
first = first->next;
second = second->next;
}
second->next = second->next->next;//删除操作
struct ListNode* ans = dummy->next;
free(dummy);
return ans;
}
注:参考leetcode官方题解