题目
代码实现:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int getLength(struct ListNode* head){
int length = 0;
while(head != NULL){
length++;
head = head->next;
}
return length;
}
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
int len = getLength(head);
int num = len - n;
struct ListNode *node;
node = malloc(sizeof(struct ListNode));
node->val = 0;
node->next = head;
struct ListNode* cur = node;
while(num>0){
cur = cur -> next;
num--;
}
cur->next = cur->next->next;
struct ListNode * res = node->next;
free(node);
return res;
}
结果: