美文网首页
Remove Nth Node From End of List

Remove Nth Node From End of List

作者: 一枚煎餅 | 来源:发表于2016-10-06 06:32 被阅读0次
Remove Nth Node From End of List.png

解題思路 :

此類型題目 head 也有可能是被移除的候選人 最簡單的方法就是建立 dummy node 去連接 head 然後重設 head = dummy 接著就不用煩惱 head 遺失的問題了 其他問題可以用 2 pointer 方式解決

C++ code :

<pre><code>
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) {
   //create a dummy node in front of the head
   ListNode *first = new ListNode(0);
   first->next = head;
   ListNode *second = first;
   //head can be remove, so it's better to reset the head = the dummy node
   head = first;
   //for getting the length - n (distance) 
   for(int i = 0; i < n; i++)
   {
       first = first->next;
   }
   while(first->next)
   {
       first = first->next;
       second = second->next;
   }
   first = second->next;
   second->next = first->next;
   delete first;
   return head->next;
}

};

相关文章

网友评论

      本文标题:Remove Nth Node From End of List

      本文链接:https://www.haomeiwen.com/subject/pxjeyttx.html