[问题] Leetcode 19 removeNthFromEnd

楼主: buyfood (buyfood)   2024-02-23 17:25:05
各位高手大家好,今天练习这题时有些疑惑想请教
题目:https://leetcode.com/problems/remove-nth-node-from-end-of-list/descripti
on/
一开始写出的做法如下:
```
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
static int i = 0;
if (head->next != NULL)
{
head->next = removeNthFromEnd(head->next, n);
}
i++;
if (n == i)
{
return head->next; // skip yourself
}
else
{
return head;
}
}
};
```
在Leetcode上无法通过([1], 1)与([1,2], 1)这两个测试
回传结果是[1]与[1,2],也就是并没有成功移除node
我知道这段code并没有实际删除node,只是忽略掉
但走访起来应该跟正确答案相符,且在vs上测试可以得到正确答案
目前已知:
1. 不建议用static变量
2. 会有mem leak的问题
但神奇的事情发生了,我把static换成call by reference的做法,就通过leetcode的测
试了?!?
```
class Solution {
public:
ListNode* removeNthFromEnd2(ListNode* head, int& n) {
if (head->next != NULL)
{
head->next = removeNthFromEnd2(head->next, n);
}
n

Links booklink

Contact Us: admin [ a t ] ucptt.com