举栗子:
剑指 Offer II 021. 删除链表的倒数第 n 个结点
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int n, k;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) :val(x), next(nullptr) {}
};
ListNode* create()
{
auto dummy = new ListNode(-1), cur = dummy;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
auto p = new ListNode(x);
cur = cur->next = p;
}
auto head = dummy->next;
delete dummy;
return head;
}
void print(ListNode *head)
{
for (auto p = head; p; p = p->next)
cout << p->val << ' ';
cout << endl;
}
ListNode* deleteKthFromEnd(ListNode* head, int k)
{
auto dummy = new ListNode(-1);
dummy->next = head;
auto p = dummy;
for (int i = 0; i < n - k; i ++ ) p = p->next;
auto tmp = p->next;
p->next = p->next->next;
delete tmp;
head = dummy->next;
delete dummy;
return head;
}
int main()
{
cin >> n >> k; //n是链表中结点个数, k是待删除链表中倒数第k个结点
ListNode* head = create();
print(head);
head = deleteKthFromEnd(head, k);
print(head);
return 0;
}