c++|【华为外包面试】删除链表的倒数第 n 个结点,并且返回链表的头结点

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
例如:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

/** * 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) {} };

【c++|【华为外包面试】删除链表的倒数第 n 个结点,并且返回链表的头结点】代码:
#include struct LinkNode { int data; LinkNode* pNext; }; LinkNode* GetLastNNode(LinkNode* head,int n) { if (head==nullptr||n<=0) { return nullptr; } int numOfList = 0; LinkNode* p = head; while (p!=nullptr) { p = p->pNext; numOfList++; } if (n > numOfList) { // 需要删除的节点不在链表里 return head; } else if(n==numOfList) { return head->pNext; } int toDelete = numOfList - n-1; p = head; while (toDelete>0) { p = p->pNext; } //LinkNode* toDelete = p->pNext; p->pNext = p->pNext->pNext; return head; }int main() { LinkNode* head= (LinkNode*)malloc(sizeof(LinkNode)); head->data = https://www.it610.com/article/0; head->pNext = nullptr; LinkNode* iter = head; int length = 6; for (int i = 1; i < length; i++) { LinkNode *p = (LinkNode*)malloc(sizeof(LinkNode)); p->data = https://www.it610.com/article/i; p->pNext = nullptr; iter->pNext = p; iter = iter->pNext; } LinkNode* result = GetLastNNode(head->pNext, 4); while (result!=nullptr) { std::cout << result->data << std::endl; result = result->pNext; } return 0; }

    推荐阅读