剑指 Offer II 021. 删除链表的倒数第 n 个结点
给定一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode* p=head;
struct ListNode* s;
int len=0;
int i=0;
while(p!=NULL){
len++;
p=p->next;
}
if(len==1&&n==1) return NULL;
printf("%d %d",len,len-n);
if(len==n) return head->next;
p=head;
while(i<=len-n-2){
i++;
p=p->next;
}
s=p->next;
p->next=s->next;
return head;
}