在自己的main函数下通过的代码片段:
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* removeNthFromEnd(struct
ListNode* head, int n)
{
int cout=0,i=0;
struct ListNode *node,*p,*h;
h=p=head;
while(h->next!=NULL)
{
cout++;
h=h->next;
}
if(cout==0)
{
p=p->next;
head->next=NULL;
}
while(head->next!=NULL)
{
if(i==cout-n)
{
if(i!=0)
{
node->next=head->next;
head=node;
break;
}
else if(i==0)
{
p=p->next;
break;
}
}
node=head;
i++;
head=head->next;
}
return p;
}
main函数:
int main()
{
struct ListNode *p,*head,*l,*head2;
int n;
p=(struct ListNode*)malloc(sizeof(struct ListNode*));
head=p;
p->val=0;
p->next=NULL;
do
{
scanf("%d",&p->val);
l=(struct ListNode*)malloc(sizeof(struct
ListNode*));
l->val=0;
l->next=NULL;
p->next=l;
p=p->next;
}while(getchar()!='\n');
scanf("%d",&n);
head2=removeNthFromEnd(head,n);
while(head2->next!=NULL)
{
printf("%d",head2->val);
head2=head2->next;
}
return 0;
}
在leetcode中通过的代码片段:
/**
*
Definition for singly-linked list.
*
struct ListNode {
*
int val;
*
struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct
ListNode* head, int n)
{
int cout=1,i=0;
struct ListNode *node,*p,*h;
h=p=head;
while(h->next!=NULL)
{
cout++;
h=h->next;
}
if(cout==1)
{
p=p->next;
head=NULL;
}
while(head!=NULL)
{
if(i==cout-n)
{
if(i!=0)
{
node->next=head->next;
head=node;
break;
}
else if(i==0)
{
p=p->next;
break;
}
}
node=head;
i++;
head=head->next;
}
return p;
}