#include
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x), next(nullptr){}
};
class solution{
public:
ListNode *remove(ListNode *head, int k){
//fast先移动k个结点,这样当fast->next=nullptr时,slow->next就是要删除的结点
ListNode *fast = head, *slow = head, *p = head;
int size = 0;
while(p){
p = p -> next;
++size;
}
if(k == size ){
head = head -> next;
}
else if(k == 1 && fast -> next == nullptr){
delete head;
return nullptr;
}
else{
while(k > 0 && fast -> next != nullptr){
fast = fast -> next;
--k;
}
while(fast -> next != nullptr){
fast = fast -> next;
slow = slow -> next;
}
slow -> next = slow -> next -> next;
}
return head;
}
};
int main(){
ListNode *head = new ListNode(0);
ListNode *p = head;
for(int i = 1; i < 10; ++i ){
ListNode *temp = new ListNode(i);
p -> next = temp;
p = p -> next;
}
p = head;
solution s;
s.remove(p,2);
p = head;
while(p != nullptr){
cout << p -> val;
p = p -> next;
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)