python - 如何在python中一次性找到链表的中间元素?

标签 python algorithm list data-structures linked-list

我正在尝试解决一个链表问题,使用 python 一次性找到中间元素。有人可以查看我的代码并建议最好的方法吗?

  class Node(object):
      def __init__(self, data=None, next=None):
          self.data = data
          self.next = next
      def __str__(self):
          return str(self.data)

  def print_nodes(node):
      while node:
          print node
          node = node.next

  def find_middle(node):
      while node:
          current = node
          node = node.next
          second_pointer = node.next
          next_pointer = second_pointer.next
          if next_pointer is None:
              return "Middle node is %s" % str(current)

  node1 = Node(1)
  node2 = Node(2)
  node3 = Node(3)
  node4 = Node(4)
  node5 = Node(5)

  node1.next = node2
  node2.next = node3
  node3.next = node4
  node4.next = node5

  print find_middle(node1)

最佳答案

我合并了您创建、查找和打印的所有方法。

class Node(object):
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next
    def __str__(self):
        return str(self.data)

def create_linked_list(n):
    """Creating linked list for the given
       size"""
    linked_list = Node(1)
    head = linked_list
    for i in range(2, n):
        head.next = Node(i)
        head = head.next
    return linked_list

def print_linked_list(node):
    """To print the linked list in forward"""
    while node:
        print '[',node,']','[ref] ->',
        node = node.next
    print '-> None'

def find_middle1(node):
    tick = False
    half = node
    while node:
        node = node.next
        if tick:
            half = half.next
        tick = not tick
    return "Middle node is %s" % str(half)

def find_middle2(node):
    list = []
    while node:
        list.append(node)
        node = node.next
    return "Middle node is %s" % str(list[len(list)/2])


node = create_linked_list(10)
print_linked_list(node)

print find_middle1(node)
print find_middle2(node)

输出:

[ 1 ] [ref] -> [ 2 ] [ref] -> [ 3 ] [ref] -> [ 4 ] [ref] -> [ 5 ] [ref] -> [ 6 ] [ref] -> [ 7 ] [ref] -> [ 8 ] [ref] -> [ 9 ] [ref] -> -> None
Middle node is 5
Middle node is 5

关于python - 如何在python中一次性找到链表的中间元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20320445/

相关文章:

c# - 如何在 C# 中对具有原始顺序的列表进行排名

python - Django "extra"查询

python - 在 Scikit-Learn 中设置多个算法试验时遇到问题

java - 公共(public)(静态)swap() 方法与冗余(非静态)私有(private)方法

java - 将多条记录添加到 List<List<Object>>

python - 在 Python 中取消列出以使用 itertools.product

python - 当我用 tf.keras 替换 keras 时模型坏了

python - 如何统计图像中特定尺寸的粒子数量?

algorithm - Dijkstra 算法修改

algorithm - 后序图遍历?