C++代码:
int length=0,a=0,b;
ListNode*ptr=head;
if(head==NULL)
{
return head;
}
while(ptr->next!=NULL)
{
length++;
ptr=ptr->next;
}
if(length+1==n)
{
return head->next;
}
else
{
ptr=head;
b=length-n+1;
while(ptr->next!=NULL)
{
a++;
if(a==b)
{
ptr->next=ptr->next->next;
break;
}
ptr=ptr->next;
}
}
return head;
先判断链表元素是否为空,获得链表长度length+1,当n=链表长度(length+1)时,返回head->next,否则用一循环删除目标节点,程序结束。