给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。 例如: 输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5] 提示: 链表中结点的数目为 sz 1 <= sz <= 30 0 <= Node.val <= 100 1 <= n <= sz
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
}
};
代码:
#include <iostream>
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;
}
p->pNext = p->pNext->pNext;
return head;
}
int main()
{
LinkNode* head= (LinkNode*)malloc(sizeof(LinkNode));
head->data = 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 = 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;
}
|