【问题标题】:What is sytanx for -> in linked list python链表python中->的语法是什么
【发布时间】:2017-01-14 01:27:37
【问题描述】:

大家好,我正在尝试在下面的链接列表中打印 (2->None, 3),但出现语法错误。有人可以帮我解决这个语法由于某种原因在谷歌上找不到。代码如下:

class Node(object):

   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node

def Insert(head, data):
    if head == None:
        head = Node(data)
        print(head)
    else: 
        current = head 
        while current.next != None: 
            current = current.next 
        current.next = Node(data)
    return head
print Insert(2->None, 3) # -> is bringing a syntax error, how do I write this in python 2.7?

【问题讨论】:

  • -> 在 Python 语法中不存在。你想用 2->None 做什么?你期待什么结果?
  • @furas 有没有类似的东西?我正在尝试打印此输入:2 --> NULL,data = 3 结果:2 --> 3 --> NULL in sublimetext。
  • 当您说2->None 时,您是在考虑另一种语言的语法吗?什么语言...从示例中我看不出你想要什么。
  • @Johnny:你认为-> 是什么意思?向我们询问-> 的正确语法就像向我们询问“fishbob”的日文翻译一样;不知道你想表达什么,我们无法告诉你如何正确表达。
  • @AnthonyPham:但是在 C 中使用 -> 也没有任何意义,至少有 3 个原因,所以这并没有真正的帮助。

标签: python linked-list


【解决方案1】:

老实说,我认为您首先对如何实现链表感到困惑。如果您想要以下形式的链表:

[2] -> [3] -> [None]

然后你需要向后插入每个元素。首先是None,然后是3,然后是2。您还需要将您的插入方法 inside 放在一个类中,因为您需要保存状态。这是我的建议:

class Node(object):
    def __init__(self, data, next_node=None):
        self.data = data
        self.next_node = next_node

# Create a class not a function because we need to save state
# More specficly, we need to create a "global" variable which 
# keeps track of the head of the linked list.
class LinkedList(object): 
    def __init__(self):
        self.head = None

    # Put the insert function inside of of the class.
    # That way, we can save and load the state of self.head.
    def insert(self, data):
        new_node = Node(data, self.head)
        self.head = new_node

# demo
ll = LinkedList()
# insert the elements in the reverse order you want  
# them to appear.
ll.insert(None)
ll.insert(3)
ll.insert(2)

print("Head:", ll.head.data) # Head: 2
print("Middle:", ll.head.next_node.data) # Middle: 3
print("Tail:", ll.head.next_node.next_node.data) # Tail: None

另外,我也建议进行一些研究。如this article。或者只是 google Linked List in Python 并浏览一些结果。

【讨论】:

  • 谢谢,这比hackerrank挑战更深入,哈哈。 @叶子
  • 我的荣幸,@Johnny。
【解决方案2】:

我感觉你只想插入None 作为@leaf 所说的第一个参数。那样的话,直接用None

print Insert(None, 3)

-> 目前在 Python 中不存在。这是@leaf 的评论:

如果您不想传入任何内容,只需传入NoneInsert(None, 3)。 Python 没有你想的那种意义上的指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 2016-09-11
    • 1970-01-01
    • 2017-09-15
    • 2012-03-22
    相关资源
    最近更新 更多