问题1:选用c环境,代码输入后编译显示 line 17 (代码中双星号包裹的地方):dereferencing pointer to incomplete type ‘struct listNode’错误
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
int length;
int s;
struct listNode *p;
struct listNode *q;
p=(struct ListNode*)malloc(sizeof(struct ListNode));
q=(struct ListNode*)malloc(sizeof(struct ListNode));
**p->next= *head;**
q->next = *head;
length = 0;
s=0;
if(p == NULL || n<0)
{
return 0;
}
while(p->value!=NULL)
{
p=p->next;
length++;
}
if (length < n)
{
return 0;
}
while(s!=length-n-1)
{
if(n==0)
{
q->next = NULL;
break;
}
q->next=q->next->next;
s++;
}
}
解决1:未找到未定义的地方,改为选择c++环境,问题解决
问题2:返回结果删除了数字12,
解决2:未考虑length=0,删除头节点的情况,加入该情况的判断条件后,通过,代码如下:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int length;
int s;
// ListNode* dummy = new ListNode(-1);
//dummy->next = head;
//head = dummy;
ListNode* p;
ListNode* q;
p= head;
q = head;
length = 0;
s=0;
if(head == NULL || n<0)
{
return 0;
}
while(head!=NULL)
{
head=head->next;
length++;
}
if (length < n)
{
return 0;
}
else if(length==n)
{
return p->next;
}
else
{
while(s!=length-n-1)
{
if(n==0)
{
q->next = NULL;
break;
}
q=q->next;
s++;
}
q->next=q->next->next;
}
return p;
}
};