问题
思路
需要注意一点,当n==len的情形需要特殊处理。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int len = 0;
for( ListNode* p = head; p!=NULL; p=p->next ) len++;
if(n==len)
{
ListNode* p = head;
head = head->next;
delete p;
p = NULL;
return head;
}
int cnt = len-n;
ListNode* pre = NULL;
ListNode* p = head;
for(int i = 0; i < cnt; ++i){
pre = p;
p=p->next;
}
pre->next = p->next;
delete p;
p = NULL;
return head;
}
};
思路1
本省可以两个指针。但是边界情况太多。
所以,先算出节点个数了。
边界情况比较多,小心!
代码1
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head) return NULL; // 1
ListNode* p = head;
int cnt = 0;
while(p){
++cnt;
p = p->next;
}
if(cnt < n) return NULL; // 2
if(1==cnt) return NULL; // 3
if(n==cnt){ // 4
ListNode* ret = head->next;
delete head;
return ret;
}
int k = cnt - n - 1;
std::cout << k << std::endl;
p = head;
for(int i = 0; i < k; ++i){
p = p->next;
}
ListNode* q = p->next;
p->next = q->next;
delete q;
return head;
}
};