最後からn番目のノードを削除
3963 ワード
/**
* 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(NULL == head || n <= 0)
return head;
ListNode *dummy = new ListNode(0);
dummy->next = head;
head = dummy;
ListNode *front = head;// , n
ListNode *back = head;//
while(n--)
{
front = front->next;
}
while(front->next)
{
front = front->next;
back = back->next;
}// back->next
back->next = back->next->next;//
return head->next;
}
};
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(NULL == head || n <= 0)
return head;
// n , NULL,
ListNode *front = head;
while(n--)
{
front = front->next;
}
if(NULL == front)
return head->next;
ListNode *back = head;
while(front->next)
{
front = front->next;
back = back->next;
}
back->next = back->next->next;
return head;
}