在 Python 中将字符串转换为链接列表



这就是我定义链接列表的方式

class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None

我正在尝试将字符串转换为链接列表

stringTotal = "abc"
head = stringToListNode(stringTotal)
#this method should return a -> b -> c 
def stringToListNode(stringTotal):
for i in stringTotal:
currentNode = ListNode(i)

如何获取字符串的下一个字母并使其成为下一个节点?

试试这个:

def stringToListNode(stringTotal):
previousNode = None
first = None
for i in stringTotal:
currentNode = ListNode(i)
if first is None:
first = currentNode
if previousNode is not None:
previousNode.next = currentNode
previousNode = currentNode
return first

一个不错的方法可能是在ListNode类上定义一个from_stringclassmethod,它将递归地为你构建一个链表并返回 head:

class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
@classmethod
def from_string(cls, s):
if s:
n = cls(s[0])
n.next = ListNode.from_string(s[1:])
return n
n = ListNode.from_string('hello')
print(n.next.next.next.next.val)
>>> 'o'

你可以创建一个insert方法作为ListNode的属性,如果next属性已经存储了ListNode的节点,则可以在属性上调用:

class ListNode(object):
def __init__(self, x=None):
self.val = x
self.next = None
def insert(self, val):
if self.val is None:
self.val = val
else:
getattr(self.next, 'insert', lambda x:setattr(self, 'next', ListNode(x)))(val)
def __str__(self):
return '{}, {}'.format(self.val, str(self.next) if self.next else '')
def __repr__(self):
return 'List(<{}>)'.format(str(self))
@classmethod
def insert_vals(cls, s):
l = cls()
for i in s:
l.insert(i)
return l
_list = ListNode.insert_vals('abc')
print(_list)

输出:

List(<a, b, c, >)

但是请注意,在方法insert中完成的操作也可以作为简单函数执行,但是,它不如实例属性干净:

class ListNode(object):
def __init__(self, x=None):
self.val = x
self.next = None
def __str__(self):
return '{}, {}'.format(self.val, str(self.next) if self.next else '')
def __repr__(self):
return 'List(<{}>)'.format(str(self))
def insert_val(_l:ListNode, value:str) -> None:
if _l.val is None:
_l.val = value
else:
if isinstance(_l.next, ListNode):
insert_val(_l.next, value)
else:
_l.next = ListNode(value)
_l = ListNode()
for i in 'abc':
insert_val(_l, i)
>>>_l

输出:

List(<a, b, c, >) 

相关内容

  • 没有找到相关文章

最新更新