删除链表的倒数第 N 个结点
给你一个链表,删除链表的倒数第 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]
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){
if(head==nullptr) return nullptr;
ListNode* dummy = new ListNode(0,head);
ListNode* first=dummy;
ListNode* second=dummy; //快慢指针找环的入口,快指针到终点时慢指针为答案
for(int i=0;i<n;i++){
first=first->next;
}
while(first->next!=nullptr){
first=first->next;
second=second->next;
}
second->next=second->next->next;
return dummy->next;
}
}
acm模式:
#include<iostream>
using namespace std;
typedef 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){}
}ListNode;
int main(){
int N;
while(cin>>N){
bool flag=true;
ListNode* head=new ListNode;
ListNode* cur=head;
for(int i=0;i<N;++i){
int x;
cin>>x;
if(flag){
head->val=x;
flag=false;
continue;
}
cur->next=new ListNode(x);
cur=cur->next;
}
int k;
cin>>k;
ListNode* first=head;
ListNode* second=head;
bool flag1=true;
if(k==0){
cout<<0<<endl;
continue;
}
for(int i=0;i<k;++i){
if(first!=nullptr) first=first->next;
else {
flag1=false;
cout<<"NULL"<<endl;
break;
}
}
while(flag1 && first!=nullptr){
first=first->next;
second=second->next;
}
if(flag1){
cout<<second->val<<endl;
}
}
return 0;
}