题目
只使用一趟扫描,删除链表的倒数第 n 个结点,并且返回链表的头结点。
思想
使用快慢指针,快指针先移动,当快慢指针结点数差为n时就可以一起移动,当快指针为空时循环结束。
代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
int i = 0;
struct ListNode *first;
struct ListNode *last;
first = head;
last = head;
while(i++ <= n)
first = first->next;
while(first != NULL) {
last = last->next;
first = first->next;
}
last->next = last->next->next;
return head;
}