这道链表的题可以给一下提升
这个题目用双指针来解,就可以忽略链表的长度信息,绝对位置信息。通过两个链表的距离来操作。
距离通过给定的n来移动。
1.num1,num2,都指向头部。
2.通过for,移动num2到与num1距离n的位置
for(int i=0;i<n;i++){
num2=num2->next;
}
3.把num2移到最后,num2移动一次,num1移动一次,此时2到最后,1到倒数第n;
即可进行操作。
ps:这里默认的是第三步的num2没到最后,其实如果在3时,num2到了最后,意味着移除的就是头,操作 return head->next;
首先 使用ListNode *num1=head;
是有一个指针指向链表头部,而不是复制了一个链表,对这个指针进行操作就是对链表的操作。
/** 战胜 21%
* 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) {
// double points
if(head==NULL||head->next==NULL){
return NULL;
}
ListNode * newHead=head;
ListNode *num1=head;
ListNode *num2=head;
for(int i=0;i<n;i++){
num2=num2->next;
if(num2==NULL) return head->next;
}
while(num2->next!=NULL){
num1=num1->next;
num2=num2->next;
}
num1->next=num1->next->next;
return head;
}
};