题目描述
- 删除链表的倒数第 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) {
}
};
解
/**
* 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* head_save = head;
map<int,ListNode*> point ;//vector<(ListNode*) > point;
int i;
for(i=0;head!= nullptr;head=head->next){
point[i] = head;
i++;//记录有几个元素了
}
if(i==1) return nullptr;
point[i-1-n]->next = point[i-n]->next;
return head_save;
}
};;
- 未通过用例
[1,2]
2
/**
* 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* head_save = head;
map<int,ListNode*> point ;//vector<(ListNode*) > point;
int i;
for(i=0;head!= nullptr;head=head->next){
point[i] = head;
i++;//记录有几个元素了
}
if(i==1) return nullptr;
if( (i-1-n)==-1){
return point[1];
}else{
point[i-1-n]->next = point[i-n]->next;
}
return head_save;
}
};
本文探讨如何在链表中删除指定位置的倒数第n个节点,通过使用map数据结构实现常数时间复杂度的查找,提供了一个优化的链表操作方法。
358

被折叠的 条评论
为什么被折叠?



