简体   繁体   English

链表中高效的“插入”功能

[英]Efficient “Insert” function in linked list

In an interview I was asked to write an insert function for linked list in such a way that after the insertion, the element towards the head side of the inserted element should be greater and the tail side should be smaller when compared to inserted element. 在一次采访中,我被要求编写一种用于链表的插入函数,使得插入后,与插入的元素相比,插入元素朝向头部的元素应该更大,而朝向背面的元素应该更小。

I had implemented the following steps in my code: 我在代码中实现了以下步骤:

  1. initially sort the linked list in descending order. 最初按降序对链接列表进行排序。
  2. get the element. 获取元素。
  3. insert the element in such way that the linked list will be in descending order even after insertion. 插入元素时,即使插入后链表也将按降序排列。

But I was told that my way was not efficient. 但是我被告知我的方法效率不高。

Please let me know if there are efficient way to achieve the same. 请让我知道是否有有效的方法来实现这一目标。

Sort is an O(n log n) operation. 排序是O(n log n)操作。 If you read the question carefully they never say the list should be sorted, so don't do the sort operation. 如果您仔细阅读了问题,他们将永远不会说应该对列表进行排序,因此请不要执行排序操作。 What you should do instead is start with a new list with only your element, then for each element of the original list append it either to the front (if greater than the new element) or otherwise at the back. 相反,您应该做的是从仅包含您的元素的新列表开始,然后对于原始列表的每个元素,将其追加到前面(如果大于新元素),否则追加到后面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM