题目描述
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
C++
我的思路,真low
/**
* 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) {
if(head==nullptr || n==0) return head;
if(head->next==nullptr && n==1) return nullptr;
vector<ListNode*> s;
ListNode * cur=head;
while(cur){
s.push_back(cur);
cur=cur->next;
}
int len=s.size();
if(len-n==0) return head->next;
if(len-n<0) return nullptr;
ListNode * pre=s[len-n-1]; //要被删除的节点的前一个节点
pre->next=pre->next->next;
return head;
}
};
大佬的思路,真6
/**
* 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 {
/*思路:快慢指针,妙啊 快慢指针相同起点,快指针先走N步,然后快慢一起走,快指针的下一个节点为空的时候,慢指针的下一个节点就是要删除的节点*/
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head) return nullptr;
ListNode * fast=head;
ListNode * slow=head;
for(int i=0;i<n;i++){
fast=fast->next;
}
if(!fast)
return head->next; //删除第一个节点的情况
while(fast->next){
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return head;
}
};
再来一个更快的
/**
* 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 {
/*思路:递归,一直递归递归递归,在返回的时候记录次数,注意第n次返回的时候*/
public:
int count=0; //记录递归返回次数
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head) return nullptr;
head->next=removeNthFromEnd(head->next,n);
count++; //记录返回次数
if(count==n) return head->next; //把第N个节点删掉
return head;
}
};
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
/*递归*/
class Solution {
int count=0;
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null) return null;
head.next=removeNthFromEnd(head.next,n);
count++;
if(count==n) return head.next; //这里把第n个节点删除
return head;
}
}