一、题目
删除链表的倒数第n个节点_牛客题霸_牛客网 (nowcoder.com)
二、代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
if (head == nullptr)
return nullptr;
else {
ListNode* p = head;
int count = 0;
int sum = 0;
while (p != nullptr) {
sum++;
p = p->next;
}
p = head;
if (count == sum - n)//删除的是正向数的第一个结点
{
head = head->next;
free(p);
return head;
}
else //删除的不是正向数的第一个结点
{
count=1;
while (count != sum - n)//找到倒数n+1个结点
{
count++;
p = p->next;
}
ListNode* tmp = p->next;
p->next = p->next->next;
free(tmp);
return head;
}
}
}
};