https://leetcode.com/problems/remove-nth-node-from-end-of-list/
以后遇到指针的题一定要自己手画一画,即使再简单,然后一定保证用眼睛debug之后1A!!! 否则太丢人。。
第一种,就是正常做法,首先测长度,然后找倒数n个点,然后删除
第二种,就是两个指针的做法,按说会比第一种快,首先first指针走n步,然后first second一起走,直到first走到头
trick在于: n==len的时候,直接删除第一个结点就行。 一定注意释放内存 包括特殊情况处理的时候释放内存 否则太丢人,,
第一种
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <stack>
using namespace std;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
int calLen(ListNode *h){
int cnt=0;
while(h) {
h = h->next;
cnt++;
}
return cnt;
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
int len=calLen(head);
len -= n;
if(len == 0)return head->next;
ListNode *h = head;
while(len > 1){
h = h->next;
len--;
}
ListNode *tmp = h->next;
h->next = h->next->next;
delete tmp;
return head;
}
ListNode * createFromVector(vector <int> ivec) {
ListNode* ret = NULL,*head=NULL;
for(int i=0;i<ivec.size(); i++) {
if(i == 0) {
add(ret, ivec[i]);
head = ret;
} else {
add(ret->next, ivec[i]);
ret = ret->next;
}
}
return head;
}
void add(ListNode* &ret, int v) {
ret = new ListNode(v);
}
};
int main() {
//freopen("in22.txt", "r", stdin);
Solution s;
int n,m;
while(cin >> n) {
vector <int> ivec;
for(int i=0; i<n; i++) {
int t;
cin >> t;
ivec.push_back(t);
}
cin >> m;
ListNode *h = s.createFromVector(ivec);
h = s.removeNthFromEnd(h, m);
while(h) {
cout << h->val << endl;
h = h->next;
}
}
return 0;
}
第二种 4ms
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <stack>
using namespace std;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *first=head, *second=head;
int m = n;
while(m > 0) {
first = first->next;
m--;
}
if(first == NULL){
ListNode *tmp = head;
head = head->next;
delete tmp;
return head;
}
while(first->next) {
first = first->next;
second = second->next;
}
ListNode *tmp = second->next;
second ->next = second->next->next;
delete tmp;
return head;
}
ListNode * createFromVector(vector <int> ivec) {
ListNode* ret = NULL,*head=NULL;
for(int i=0;i<ivec.size(); i++) {
if(i == 0) {
add(ret, ivec[i]);
head = ret;
} else {
add(ret->next, ivec[i]);
ret = ret->next;
}
}
return head;
}
void add(ListNode* &ret, int v) {
ret = new ListNode(v);
}
};
int main() {
freopen("in22.txt", "r", stdin);
Solution s;
int n,m;
while(cin >> n) {
vector <int> ivec;
for(int i=0; i<n; i++) {
int t;
cin >> t;
ivec.push_back(t);
}
cin >> m;
ListNode *h = s.createFromVector(ivec);
h = s.removeNthFromEnd(h, m);
while(h) {
cout << h->val << endl;
h = h->next;
}
}
return 0;
}