/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
if(head==NULL||head->next==NULL)
{
return NULL;
}
struct ListNode* p = head;
struct ListNode* q = head;
for(int i = 0; i < n; i++) {
if(q!=NULL)
{
q = q->next;
}
}
if(q == NULL) {
return head->next;
}
while(q->next!=NULL)
{
p=p->next;
q=q->next;
}
if(p!=NULL&&p->next!=NULL){
p->next=p->next->next;
}
return head;
}
上面是2018年4月25日写的垃圾code。。。。。根据提示修改通过了。。。
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode* HEAD1;
struct ListNode* HEAD2;
HEAD1=head;
HEAD2=head;
for(int i=0;i<n;i++) //take pointer HEAD1 n places ahead of HEAD2
{
HEAD1=HEAD1->next;
if(!HEAD1) // when we have to delete the first node
return head->next;
}
while(HEAD1->next) //take HEAD1 to last node so that HEAD2 is 1 behind the node we want to delete
{
HEAD2=HEAD2->next;
HEAD1=HEAD1->next;
}
HEAD2->next=HEAD2->next->next; // delete the node next to HEAD2
return head;
这代码就很牛!简单明了。