题目
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
思路
双指针找到倒数第n个节点,再把该节点删除。
代码
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* removeNthFromEnd(ListNode* head, int n) {ListNode *first=head,*second=head,*last=head;int cnt=0;if(head->next==nullptr){return nullptr;}while(second){second=second->next;cnt+=1;if(cnt==n){break;}}while(second){last=first;first=first->next;second=second->next;}if(first==head){head=head->next;}else{last->next=first->next;}return head;}
};