您的位置:首页 > Web前端 > Node.js

leetcode: Remove Nth Node From End of List

2013-05-05 12:34 267 查看
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

if (head == NULL)
return NULL;

ListNode *pCur;
ListNode *pPreN;

if (n == 1 && head->next == NULL)
return NULL;

int i = n;
pCur  = head;
while (i > 0 && pCur->next != NULL)
{
pCur = pCur->next;
i--;
}

if (i != 0)
{
if (i == 1)
return head->next;
else
return NULL;
}

pPreN = head;
while (pCur->next != NULL)
{
pCur = pCur->next;
pPreN = pPreN->next;
}
pPreN->next = pPreN->next->next;

return head;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: