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

#174 Remove Nth Node From End of List

2016-08-18 11:43 453 查看
题目描述:

Given a linked list, remove the nth node from the end of list and return its head.


 Notice


The minimum number of nodes in list is n.

Have you met this question in a real interview? 

Yes

Example

Given linked list: 
1->2->3->4->5->null
,
and n = 
2
.
After removing the second node from the end, the linked list becomes 
1->2->3->5->null
.

Challenge 

Can you do it without getting the length of the linked list?

题目思路:

这题只要找到需要删除的node的前一个node的位置,就很容易办了。怎么找这个位置呢?我先用一个fast pointer,让它从dummy head开始先走n步;然后用一个slow pointer从dummy head开始跟它一起走,等fast走到最后一个node的时候,slow指向的位置就是我们想找的位置了。

Mycode (AC = 56ms):

/**
* 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
ListNode *dummy = new ListNode(0);
dummy->next = head;

// let fast ptr go n steps first
ListNode *slow = dummy, *fast = dummy;
int k = 0;
while (k < n) {
fast = fast->next;
k++;
}

// find the ptr where ptr->next is the
// element we want to delete
while (fast->next) {
slow = slow->next;
fast = fast->next;
}

// delete the element
slow->next = slow->next->next;
return dummy->next;
}
};

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