【问题标题】:Python - Linked List Issue and RelevancePython - 链表问题和相关性
【发布时间】:2019-07-02 04:53:56
【问题描述】:

我正在使用客户端/服务器进行简单的聊天。客户端在 VB 和 python中的服务器。

我想让我的服务器存储我的消息,虽然我最聪明的是构建一个链表(我是 python 新手,但 C# 更高级)。

我尝试存储的内容包括:

  • 收件人(这里称为dest)
  • 消息(称为 msg)

我不知道有多少,如果我有一条新消息给已经存储了消息的人,我会覆盖

我在课堂上试过

class tabmessage:
    def __init__(self, dest=None,msg=None, next=None): 
        self.dest = dest
        self.msg = msg
        self.next = None

这就是电话

#I create the top of the chain on the beginning
messages = tabmessage(dest='Control',msg='Message Integrity')

...然后在稍后的函数中

#Setting the top of the chain
(d,m,s) = (messages.dest,messages.msg,messages.next)
#Looking for a similar dest in chain and getting at the end at the same time
while True:
        if (d == tempdest):
            m = (tempmsg+".")[:-1]
            print("Overwrite of msg for" + d + " : " + m);
            return
        if (s is None):
            break
        (d,m,s)=(s.dest,s.msg,s.next)
#If I did not found it i try to add it to the chain
s = tabmessage(dest=(tempdest+".")[:-1],msg=(tempmsg+".")[:-1])
print("Trying to add : " + s.dest + " : " + s. msg)

最后的打印看起来不错:

尝试添加:用户:这是我的消息

但如果我这样做:

print("Trying to add : " + messages.next.dest + " : " + messages.next. msg)

发生错误(NoneType 没有 dest 元素...),所以顶部仍然是单独的。

或者如果有更聪明的方法可以在 python 中做到这一点?

【问题讨论】:

  • 为什么要使用链表?我不清楚您要完成什么,以及为什么需要滚动您自己的链表,但m = tempmsg 不会影响任何事情。它只是将tempmsg 分配给局部变量m,然后函数返回。
  • 我需要与他们的收件人一起存储一个邮件列表(它是 dest)。那我不知道有多少。在 C 或 C# 中,我会有一个使用链表。我是 Python 的新手,所以我也这么认为。
  • 我将 m = tempmsg 修改为 m = (tempmsg + ".")[:-1] 在这里新建一个字符串
  • 为什么不直接使用内置的list
  • 再一次,你只是分配给一个不会改变任何东西的局部变量m

标签: python linked-list


【解决方案1】:

如果我正确理解了您的功能,您将找到您想要的节点

if (d == tempdest):

然后你正在写你的信息并返回。因为您返回,所以将 s 分配给新节点的底部语句永远不会运行。我想你想打破那里。我不确定这是您唯一的问题,但我认为这就是您的列表没有获得额外节点的原因。

【讨论】:

  • 实际上,当没有收件人“d”存在(并且只有我想添加一个节点)时,我到达了这部分,所以当我调试时,零消息,我到达了它,但节点是未添加到链中
【解决方案2】:

我试图在更高的节点上进行操作,它可以工作。 现在我有:

#Setting the top of the chain
cunode = messages
#Looking for a similar dest in chain and getting at the end at the same time
while True:
    if (cunode.dest == tempdest):
        cunode.msg = (tempmsg+".")[:-1]
        print("Overwrite of msg for" + cunode.dest + " : " + cunode.msg);
        return
    if (cunode.next is None):
        break
    cunode = cunode.next

#If I did not found it i try to add it to the chain
cunode.next = tabmessage(dest=(tempdest+".")[:-1],msg=(tempmsg+".")[:-1])

对我来说看起来完全一样......

【讨论】:

    猜你喜欢
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 2020-12-05
    • 2016-05-19
    • 1970-01-01
    • 2017-05-23
    相关资源
    最近更新 更多