题目描述
- 删除链表的倒数第 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;
}
};