返回链表中倒数第5个元素

return 5th element from last in linked list?

本文关键字:5个 元素 倒数 链表 返回      更新时间:2023-10-16

以上问题是我在面试中被问到的。虽然我还在等待结果,但我想知道我的方法是否正确,或者是否有更好的解决方案?

 struct Node  
 {   
  int data;  
  Node * next;    
 };  
 Node *function( struct Node *head)   
 {    
    if ( ! head)   
    {   
        std::cout <<" no linked present";  
        return 0;  
    }  
    Node  *current, *temp;  
    temp = NULL;
    current = head;  
    int counter = 0;  
    while( current != NULL)   
    {
        counter ++;  
        current = current->next;   
        if( counter >= 5)   
        {
            if( temp == NULL)  
                temp = head;   
            else
            temp = temp->next;  
        }  
    }  
     return (temp);    
   }    

如果你们有更好的最佳解决方案,请贴在这里。谢谢大家山姆

对于单链表,您的解决方案应该是最优的。对于双链表,可以从后面开始。

如果您排除列表长度小于5个元素的情况,我会说下一个解决方案更优雅一些,但本质上是一样的:

Node *function( struct Node *head)  
{
   while ( head->next->next->next->next )
      head = head->next;
   return head 
}

性能方面,对于单链表,您不能做得比O(n)更好,所以所有可以改进的是可读性。

编辑:

Vlad在注释中提出了一个有趣的观点,即在循环的每次迭代中执行更多的指令。我认为这是错误的,因为指针访问只需要1 asm指令。然而,在OP的代码中:

   counter ++;  
   current = current->next;   
   if( counter >= 5)   
   {
       if( temp == NULL)  
           temp = head;   
       else
           temp = temp->next;  
   }  

是在循环中执行的指令。这样效率就低多了。自增,2个指针赋值和2个比较…

都是O(n),但对于大输入,时间是4*n还是10*n很重要。

看起来会很好。唯一的问题是您没有在代码中声明temp,也没有将其初始化为NULL。