题目:
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例2:
输入:head = [1], n = 1
输出:[]
示例3:
输入:head = [1,2], n = 1
输出:[1]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
解题代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
// 定义两个指针同时指向链表头部
struct ListNode* first = head;
struct ListNode* second = head;
// 让first指针先走n步
while(n > 0){
first = first->next;
n--;
}
// 防止只有一个节点的情况
if(first == NULL)
return head->next;
// 两个指针一起走 当first指向最后一个节点时 second正好指向倒数第n个节点的上一个
while(first->next != NULL){
first = first->next;
second = second->next;
}
// 删除倒数第n个节点
second->next = second->next->next;
return head;
}