【问题标题】:Accessing specific element of the singly linked list访问单链表的特定元素
【发布时间】:2015-07-24 00:23:47
【问题描述】:

我想创建一个函数 get_element(n),它根据元素在列表中的位置返回单链表的元素。如果我将 -1 发​​送给函数,我希望返回最后一个元素,如果它是 -2,则函数将第二个元素返回到最后一个元素,依此类推。如何在不颠倒列表或引入其他属性(大小或类似属性)的情况下做到这一点?如果我想要倒数第二个,我可以遍历列表直到 current.next.next == None,倒数第三个使用 current.next.next.next == None,但我不知道如何概括它。 如果有人能用任何语言给我写这段代码,我将不胜感激,最好是用 Python。

【问题讨论】:

  • 保留最后访问的-n 元素的队列,并在到达None 时获取其第一个元素。几乎相当于颠倒列表,但这确实是唯一的方法。

标签: python singly-linked-list


【解决方案1】:

Python 可能不是最好的选择,因为您想要的功能已经内置:

def get_element(n):
    my_list = ["The", "cat", "sat", "on", "the", "mat."]
    return my_list[n]


print get_element(0)
print get_element(-1)
print get_element(-2)

这会给:

The
mat.
the

如前所述,您可以使用队列来模拟您的问题:

import collections


def get_element(n):
    my_list = ["The", "cat", "sat", "on", "the", "mat."]

    if n >= 0:
        for index, element in enumerate(my_list):
            if index == n:
                return element

        # Return last element if beyond the range
        return element  
    else:
        queue = collections.deque(maxlen=-n)    # Used to simulate a queue

        for element in my_list:
            queue.append(element)

        return queue.popleft()


print get_element(0)
print get_element(-1)
print get_element(-2)

这会给:

The
mat.
the

【讨论】:

    猜你喜欢
    • 2018-03-23
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 2018-07-08
    相关资源
    最近更新 更多