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

时间:2018-06-26 16:15:34

标签: python linked-list

这就是我定义我的linkedList的方式

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

我正在尝试将字符串转换为linkedList

stringTotal = "abc"
head = stringToListNode(stringTotal)

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

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

3 个答案:

答案 0 :(得分:3)

尝试一下:

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

答案 1 :(得分:1)

一种不错的方法是在from_string类上定义一个ListNode类方法,该方法将为您递归构建一个链表并返回标头:

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'

答案 2 :(得分:-1)

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

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, >)