//第一种解法,遍历一次数长度,然后把头尾相连,再遍历一次
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* tem=head;
int len=0;
while(tem->next){ //这里得到的长度是真实长度-1
tem=tem->next;
len++;
}
if(len==0) return NULL;
if(len==1){
if(n==1){
head->next=NULL;
}
else head=head->next;
return head;
}
tem->next=head; //头尾相连
ListNode* tail=tem;
for( int i=0;i<len-n+1;i++){ //从最后一个节点出发,直到到达要删的节点的前一个;但如果要删的节点是表头,也不会移动
tem=tem->next;
}
ListNode* trash=tem->next; //要删的节点
tail->next=NULL; //如果要删的是最后一个,如果没有这句会把倒数第二个和头连成环
tem->next=trash->next;
if(trash==head) head=head->next;
tail->next=NULL;
return head;
}
};
//第一种解法,遍历一次数长度,然后把头尾相连,再遍历一次
class Solution