LeetCode19 --------Remove Nth Node From End of List
链表操作。
我的思路是:
1.先计算出链表的长度len,再根据其求出要删除的元素的正序。
2.考虑头结点的操作。
代码:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode*ptr1 = head;
int count =1;
while(ptr1->next != NULL)
{
ptr1 = ptr1->next;
count ++;
}
n= count - n;
if(n == 0)
{
ptr1=head;
head=head->next;
delete ptr1;
return head;
}
ptr1 = head;
ListNode*ptr2=head;
while(n --)
{
ptr1= ptr1->next;
}
while(ptr2!=ptr1&&ptr2->next != ptr1)
{
ptr2=ptr2->next;
}
ptr2->next = ptr1->next;
delete ptr1;
return head;
}
};
1189

被折叠的 条评论
为什么被折叠?



