struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
if (head == NULL||n<=0 )return head;
if (head->next == NULL && n == 1)return NULL;
struct ListNode* p = head;
int len = 1;
while (p->next != NULL) {
p = p->next;
len++;
}//len为链表结点个数,p为尾结点
if (n == len) return head->next;//如果删除的是头结点那么返回第二个结点
struct ListNode* q = head;
int len1 = len - n-1;
while (len1--) {
q = q->next;
}//q为待删除结点的前一个结点
struct ListNode* clean = q->next;
if (n == 1) {
q->next = NULL;
}//如果待删除的是最后一个结点那么前一个节点指向空
else {
q->next = q->next -> next;
}//如果待删除的不是最后一个结点那么前一个结点指向待删除结点的下一个结点
free(clean);
return head;
}
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode* new_head=(struct ListNode*)malloc(sizeof(struct ListNode));
new_head->next = head;
struct ListNode* p = new_head;
struct ListNode* q = new_head;
n = n + 1;
while (n--)q = q->next;
while (q != NULL) {
p = p->next;
q = q->next;
}
p->next = p->next->next;
return new_head->next;
}
利用双指针和虚拟头结点来处理边界情况,
q指针遍历到N+1个位置,如果没到空则继续遍历,p则遍历到要删除结点的前一个结点
因为总长减去N就是要删去结点的位置。