題目
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
分析
簡單的鏈表操作剧腻,不多說,直接上代碼账千。
實現(xiàn)一
/**
* 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==NULL) return NULL;
int length=1;
ListNode * p=head;
while(p->next!=NULL){
p = p->next;
length++;
}
if(length>n){
p=head;
for(int i=0; i<length-n-1; i++){
p = p->next;
}
p->next=p->next->next;
}
else{
head=head->next;
}
return head;
}
};
思考一
提交之后發(fā)現(xiàn)自己只打敗了2.8%的用戶,內(nèi)心是崩潰的品姓。簡單的鏈表刪除還有什么花頭嗎谈跛。遂查看別人的代碼以及題解攀细,發(fā)現(xiàn)也差不多啊箫踩。后來發(fā)現(xiàn)是提交時段的問題,重新用這段代碼提交一次就好了=_=