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

LintCode 174:Remove Nth Node From End of List

2017-08-26 21:49 477 查看
Description:
Given a linked list, remove the nth node from the end of list and return its head.

Note:

需要注意的边界情况:

当需要删除的结点是head结点时,head会发生改变。

当n超过结点个数时,表明没有需要删除的结点。

Code:

/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode *removeNthFromEnd(ListNode *head, int n) {
// write your code here
int i;
ListNode* first = head;
ListNode* second = head;
bool flag = false;
for(i=0;i<n-1;i++){
if(first)
first=first->next;
else
break;
}
if(i<n-1||!first)
return head;
while(first->next&&first->next->next){
first=first->next;
second=second->next;
flag = true;
}
ListNode * deleted;
if(!flag){
deleted = head;
head=head->next;
}
else{
deleted = second->next;
second->next = deleted->next;
}
delete deleted;
return head;
}
};

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