//#19 Remove Nth Node From End of List
//4ms 100%
#include <iostream>
using namespace std;
/**
* 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)
//assume this n is always valid
{
if(head == NULL) return head;
if(n == 0) return head;
ListNode *p1(head), *p2(head);
for(int i=0; i<n; i++)
{
p2 = p2->next;
}
//cout << "ok1\n";
if(p2 == NULL)
{
head = head->next;
return head;
}
//cout << "ok2\n";
while(p2->next != NULL)
{
p1 = p1->next;
p2 = p2->next;
}
p1->next = p1->next->next;
return head;
}
};
[Leetcode]#19 Remove Nth Node From End of List
最新推荐文章于 2023-12-11 10:06:36 发布